user.go 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "bytes"
  7. "container/list"
  8. "crypto/sha256"
  9. "crypto/subtle"
  10. "encoding/hex"
  11. "fmt"
  12. "image"
  13. _ "image/jpeg"
  14. "image/png"
  15. "os"
  16. "path/filepath"
  17. "strings"
  18. "time"
  19. "unicode/utf8"
  20. "github.com/Unknwon/com"
  21. "github.com/go-xorm/xorm"
  22. "github.com/nfnt/resize"
  23. "golang.org/x/crypto/pbkdf2"
  24. log "gopkg.in/clog.v1"
  25. "github.com/gogits/git-module"
  26. api "github.com/gogits/go-gogs-client"
  27. "github.com/gogits/gogs/models/errors"
  28. "github.com/gogits/gogs/pkg/avatar"
  29. "github.com/gogits/gogs/pkg/setting"
  30. "github.com/gogits/gogs/pkg/tool"
  31. )
  32. type UserType int
  33. const (
  34. USER_TYPE_INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  35. USER_TYPE_ORGANIZATION
  36. )
  37. // User represents the object of individual and member of organization.
  38. type User struct {
  39. ID int64
  40. LowerName string `xorm:"UNIQUE NOT NULL"`
  41. Name string `xorm:"UNIQUE NOT NULL"`
  42. FullName string
  43. // Email is the primary email address (to be used for communication)
  44. Email string `xorm:"NOT NULL"`
  45. HideEmail bool
  46. Passwd string `xorm:"NOT NULL"`
  47. LoginType LoginType
  48. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  49. LoginName string
  50. Type UserType
  51. OwnedOrgs []*User `xorm:"-"`
  52. Orgs []*User `xorm:"-"`
  53. Repos []*Repository `xorm:"-"`
  54. Location string
  55. Website string
  56. Rands string `xorm:"VARCHAR(10)"`
  57. Salt string `xorm:"VARCHAR(10)"`
  58. Created time.Time `xorm:"-"`
  59. CreatedUnix int64
  60. Updated time.Time `xorm:"-"`
  61. UpdatedUnix int64
  62. // Remember visibility choice for convenience, true for private
  63. LastRepoVisibility bool
  64. // Maximum repository creation limit, -1 means use gloabl default
  65. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  66. // Permissions
  67. IsActive bool // Activate primary email
  68. IsAdmin bool
  69. AllowGitHook bool
  70. AllowImportLocal bool // Allow migrate repository by local path
  71. ProhibitLogin bool
  72. // Avatar
  73. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  74. AvatarEmail string `xorm:"NOT NULL"`
  75. UseCustomAvatar bool
  76. // Counters
  77. NumFollowers int
  78. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  79. NumStars int
  80. NumRepos int
  81. // For organization
  82. Description string
  83. NumTeams int
  84. NumMembers int
  85. Teams []*Team `xorm:"-"`
  86. Members []*User `xorm:"-"`
  87. }
  88. func (u *User) BeforeInsert() {
  89. u.CreatedUnix = time.Now().Unix()
  90. u.UpdatedUnix = u.CreatedUnix
  91. }
  92. func (u *User) BeforeUpdate() {
  93. if u.MaxRepoCreation < -1 {
  94. u.MaxRepoCreation = -1
  95. }
  96. u.UpdatedUnix = time.Now().Unix()
  97. }
  98. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  99. switch colName {
  100. case "created_unix":
  101. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  102. case "updated_unix":
  103. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  104. }
  105. }
  106. func (u *User) APIFormat() *api.User {
  107. return &api.User{
  108. ID: u.ID,
  109. UserName: u.Name,
  110. FullName: u.FullName,
  111. Email: u.Email,
  112. AvatarUrl: u.AvatarLink(),
  113. }
  114. }
  115. // returns true if user login type is LOGIN_PLAIN.
  116. func (u *User) IsLocal() bool {
  117. return u.LoginType <= LOGIN_PLAIN
  118. }
  119. // HasForkedRepo checks if user has already forked a repository with given ID.
  120. func (u *User) HasForkedRepo(repoID int64) bool {
  121. _, has, _ := HasForkedRepo(u.ID, repoID)
  122. return has
  123. }
  124. func (u *User) RepoCreationNum() int {
  125. if u.MaxRepoCreation <= -1 {
  126. return setting.Repository.MaxCreationLimit
  127. }
  128. return u.MaxRepoCreation
  129. }
  130. func (u *User) CanCreateRepo() bool {
  131. if u.MaxRepoCreation <= -1 {
  132. if setting.Repository.MaxCreationLimit <= -1 {
  133. return true
  134. }
  135. return u.NumRepos < setting.Repository.MaxCreationLimit
  136. }
  137. return u.NumRepos < u.MaxRepoCreation
  138. }
  139. func (u *User) CanCreateOrganization() bool {
  140. return !setting.Admin.DisableRegularOrgCreation || u.IsAdmin
  141. }
  142. // CanEditGitHook returns true if user can edit Git hooks.
  143. func (u *User) CanEditGitHook() bool {
  144. return u.IsAdmin || u.AllowGitHook
  145. }
  146. // CanImportLocal returns true if user can migrate repository by local path.
  147. func (u *User) CanImportLocal() bool {
  148. return setting.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  149. }
  150. // DashboardLink returns the user dashboard page link.
  151. func (u *User) DashboardLink() string {
  152. if u.IsOrganization() {
  153. return setting.AppSubURL + "/org/" + u.Name + "/dashboard/"
  154. }
  155. return setting.AppSubURL + "/"
  156. }
  157. // HomeLink returns the user or organization home page link.
  158. func (u *User) HomeLink() string {
  159. return setting.AppSubURL + "/" + u.Name
  160. }
  161. func (u *User) HTMLURL() string {
  162. return setting.AppURL + u.Name
  163. }
  164. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  165. func (u *User) GenerateEmailActivateCode(email string) string {
  166. code := tool.CreateTimeLimitCode(
  167. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  168. setting.Service.ActiveCodeLives, nil)
  169. // Add tail hex username
  170. code += hex.EncodeToString([]byte(u.LowerName))
  171. return code
  172. }
  173. // GenerateActivateCode generates an activate code based on user information.
  174. func (u *User) GenerateActivateCode() string {
  175. return u.GenerateEmailActivateCode(u.Email)
  176. }
  177. // CustomAvatarPath returns user custom avatar file path.
  178. func (u *User) CustomAvatarPath() string {
  179. return filepath.Join(setting.AvatarUploadPath, com.ToStr(u.ID))
  180. }
  181. // GenerateRandomAvatar generates a random avatar for user.
  182. func (u *User) GenerateRandomAvatar() error {
  183. seed := u.Email
  184. if len(seed) == 0 {
  185. seed = u.Name
  186. }
  187. img, err := avatar.RandomImage([]byte(seed))
  188. if err != nil {
  189. return fmt.Errorf("RandomImage: %v", err)
  190. }
  191. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  192. return fmt.Errorf("MkdirAll: %v", err)
  193. }
  194. fw, err := os.Create(u.CustomAvatarPath())
  195. if err != nil {
  196. return fmt.Errorf("Create: %v", err)
  197. }
  198. defer fw.Close()
  199. if err = png.Encode(fw, img); err != nil {
  200. return fmt.Errorf("Encode: %v", err)
  201. }
  202. log.Info("New random avatar created: %d", u.ID)
  203. return nil
  204. }
  205. // RelAvatarLink returns relative avatar link to the site domain,
  206. // which includes app sub-url as prefix. However, it is possible
  207. // to return full URL if user enables Gravatar-like service.
  208. func (u *User) RelAvatarLink() string {
  209. defaultImgUrl := setting.AppSubURL + "/img/avatar_default.png"
  210. if u.ID == -1 {
  211. return defaultImgUrl
  212. }
  213. switch {
  214. case u.UseCustomAvatar:
  215. if !com.IsExist(u.CustomAvatarPath()) {
  216. return defaultImgUrl
  217. }
  218. return setting.AppSubURL + "/avatars/" + com.ToStr(u.ID)
  219. case setting.DisableGravatar, setting.OfflineMode:
  220. if !com.IsExist(u.CustomAvatarPath()) {
  221. if err := u.GenerateRandomAvatar(); err != nil {
  222. log.Error(3, "GenerateRandomAvatar: %v", err)
  223. }
  224. }
  225. return setting.AppSubURL + "/avatars/" + com.ToStr(u.ID)
  226. }
  227. return tool.AvatarLink(u.AvatarEmail)
  228. }
  229. // AvatarLink returns user avatar absolute link.
  230. func (u *User) AvatarLink() string {
  231. link := u.RelAvatarLink()
  232. if link[0] == '/' && link[1] != '/' {
  233. return setting.AppURL + strings.TrimPrefix(link, setting.AppSubURL)[1:]
  234. }
  235. return link
  236. }
  237. // User.GetFollwoers returns range of user's followers.
  238. func (u *User) GetFollowers(page int) ([]*User, error) {
  239. users := make([]*User, 0, ItemsPerPage)
  240. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.follow_id=?", u.ID)
  241. if setting.UsePostgreSQL {
  242. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  243. } else {
  244. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  245. }
  246. return users, sess.Find(&users)
  247. }
  248. func (u *User) IsFollowing(followID int64) bool {
  249. return IsFollowing(u.ID, followID)
  250. }
  251. // GetFollowing returns range of user's following.
  252. func (u *User) GetFollowing(page int) ([]*User, error) {
  253. users := make([]*User, 0, ItemsPerPage)
  254. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.user_id=?", u.ID)
  255. if setting.UsePostgreSQL {
  256. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  257. } else {
  258. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  259. }
  260. return users, sess.Find(&users)
  261. }
  262. // NewGitSig generates and returns the signature of given user.
  263. func (u *User) NewGitSig() *git.Signature {
  264. return &git.Signature{
  265. Name: u.DisplayName(),
  266. Email: u.Email,
  267. When: time.Now(),
  268. }
  269. }
  270. // EncodePasswd encodes password to safe format.
  271. func (u *User) EncodePasswd() {
  272. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  273. u.Passwd = fmt.Sprintf("%x", newPasswd)
  274. }
  275. // ValidatePassword checks if given password matches the one belongs to the user.
  276. func (u *User) ValidatePassword(passwd string) bool {
  277. newUser := &User{Passwd: passwd, Salt: u.Salt}
  278. newUser.EncodePasswd()
  279. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  280. }
  281. // UploadAvatar saves custom avatar for user.
  282. // FIXME: split uploads to different subdirs in case we have massive users.
  283. func (u *User) UploadAvatar(data []byte) error {
  284. img, _, err := image.Decode(bytes.NewReader(data))
  285. if err != nil {
  286. return fmt.Errorf("Decode: %v", err)
  287. }
  288. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  289. sess := x.NewSession()
  290. defer sess.Close()
  291. if err = sess.Begin(); err != nil {
  292. return err
  293. }
  294. u.UseCustomAvatar = true
  295. if err = updateUser(sess, u); err != nil {
  296. return fmt.Errorf("updateUser: %v", err)
  297. }
  298. os.MkdirAll(setting.AvatarUploadPath, os.ModePerm)
  299. fw, err := os.Create(u.CustomAvatarPath())
  300. if err != nil {
  301. return fmt.Errorf("Create: %v", err)
  302. }
  303. defer fw.Close()
  304. if err = png.Encode(fw, m); err != nil {
  305. return fmt.Errorf("Encode: %v", err)
  306. }
  307. return sess.Commit()
  308. }
  309. // DeleteAvatar deletes the user's custom avatar.
  310. func (u *User) DeleteAvatar() error {
  311. log.Trace("DeleteAvatar [%d]: %s", u.ID, u.CustomAvatarPath())
  312. os.Remove(u.CustomAvatarPath())
  313. u.UseCustomAvatar = false
  314. if err := UpdateUser(u); err != nil {
  315. return fmt.Errorf("UpdateUser: %v", err)
  316. }
  317. return nil
  318. }
  319. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  320. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  321. has, err := HasAccess(u.ID, repo, ACCESS_MODE_ADMIN)
  322. if err != nil {
  323. log.Error(2, "HasAccess: %v", err)
  324. }
  325. return has
  326. }
  327. // IsWriterOfRepo returns true if user has write access to given repository.
  328. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  329. has, err := HasAccess(u.ID, repo, ACCESS_MODE_WRITE)
  330. if err != nil {
  331. log.Error(2, "HasAccess: %v", err)
  332. }
  333. return has
  334. }
  335. // IsOrganization returns true if user is actually a organization.
  336. func (u *User) IsOrganization() bool {
  337. return u.Type == USER_TYPE_ORGANIZATION
  338. }
  339. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  340. func (u *User) IsUserOrgOwner(orgId int64) bool {
  341. return IsOrganizationOwner(orgId, u.ID)
  342. }
  343. // IsPublicMember returns true if user public his/her membership in give organization.
  344. func (u *User) IsPublicMember(orgId int64) bool {
  345. return IsPublicMembership(orgId, u.ID)
  346. }
  347. // IsEnabledTwoFactor returns true if user has enabled two-factor authentication.
  348. func (u *User) IsEnabledTwoFactor() bool {
  349. return IsUserEnabledTwoFactor(u.ID)
  350. }
  351. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  352. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  353. }
  354. // GetOrganizationCount returns count of membership of organization of user.
  355. func (u *User) GetOrganizationCount() (int64, error) {
  356. return u.getOrganizationCount(x)
  357. }
  358. // GetRepositories returns repositories that user owns, including private repositories.
  359. func (u *User) GetRepositories(page, pageSize int) (err error) {
  360. u.Repos, err = GetUserRepositories(&UserRepoOptions{
  361. UserID: u.ID,
  362. Private: true,
  363. Page: page,
  364. PageSize: pageSize,
  365. })
  366. return err
  367. }
  368. // GetRepositories returns mirror repositories that user owns, including private repositories.
  369. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  370. return GetUserMirrorRepositories(u.ID)
  371. }
  372. // GetOwnedOrganizations returns all organizations that user owns.
  373. func (u *User) GetOwnedOrganizations() (err error) {
  374. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  375. return err
  376. }
  377. // GetOrganizations returns all organizations that user belongs to.
  378. func (u *User) GetOrganizations(showPrivate bool) error {
  379. orgIDs, err := GetOrgIDsByUserID(u.ID, showPrivate)
  380. if err != nil {
  381. return fmt.Errorf("GetOrgIDsByUserID: %v", err)
  382. }
  383. if len(orgIDs) == 0 {
  384. return nil
  385. }
  386. u.Orgs = make([]*User, 0, len(orgIDs))
  387. if err = x.Where("type = ?", USER_TYPE_ORGANIZATION).In("id", orgIDs).Find(&u.Orgs); err != nil {
  388. return err
  389. }
  390. return nil
  391. }
  392. // DisplayName returns full name if it's not empty,
  393. // returns username otherwise.
  394. func (u *User) DisplayName() string {
  395. if len(u.FullName) > 0 {
  396. return u.FullName
  397. }
  398. return u.Name
  399. }
  400. func (u *User) ShortName(length int) string {
  401. return tool.EllipsisString(u.Name, length)
  402. }
  403. // IsMailable checks if a user is elegible
  404. // to receive emails.
  405. func (u *User) IsMailable() bool {
  406. return u.IsActive
  407. }
  408. // IsUserExist checks if given user name exist,
  409. // the user name should be noncased unique.
  410. // If uid is presented, then check will rule out that one,
  411. // it is used when update a user name in settings page.
  412. func IsUserExist(uid int64, name string) (bool, error) {
  413. if len(name) == 0 {
  414. return false, nil
  415. }
  416. return x.Where("id != ?", uid).Get(&User{LowerName: strings.ToLower(name)})
  417. }
  418. // GetUserSalt returns a ramdom user salt token.
  419. func GetUserSalt() (string, error) {
  420. return tool.RandomString(10)
  421. }
  422. // NewGhostUser creates and returns a fake user for someone who has deleted his/her account.
  423. func NewGhostUser() *User {
  424. return &User{
  425. ID: -1,
  426. Name: "Ghost",
  427. LowerName: "ghost",
  428. }
  429. }
  430. var (
  431. reservedUsernames = []string{".", "..", "*.about", "admin", "api", "assets", "avatar", "commits", "create", "css", "debug", "explore", "*.fingerprints", "help", "img", "install", "issues", "js", "less", "new", "org", "*.outages", "plugins", "pulls", "raw", "repo", "stars", "template", "*.tos", "user"}
  432. reservedUserPatterns = []string{"*.keys"}
  433. )
  434. // isUsableName checks if name is reserved or pattern of name is not allowed
  435. // based on given reserved names and patterns.
  436. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  437. func isUsableName(names, patterns []string, name string) error {
  438. name = strings.TrimSpace(strings.ToLower(name))
  439. if utf8.RuneCountInString(name) == 0 {
  440. return errors.EmptyName{}
  441. }
  442. for i := range names {
  443. if name == names[i] {
  444. return ErrNameReserved{name}
  445. }
  446. }
  447. for _, pat := range patterns {
  448. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  449. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  450. return ErrNamePatternNotAllowed{pat}
  451. }
  452. }
  453. return nil
  454. }
  455. func IsUsableUsername(name string) error {
  456. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  457. }
  458. // CreateUser creates record of a new user.
  459. func CreateUser(u *User) (err error) {
  460. if err = IsUsableUsername(u.Name); err != nil {
  461. return err
  462. }
  463. isExist, err := IsUserExist(0, u.Name)
  464. if err != nil {
  465. return err
  466. } else if isExist {
  467. return ErrUserAlreadyExist{u.Name}
  468. }
  469. u.Email = strings.ToLower(u.Email)
  470. u.HideEmail = true
  471. isExist, err = IsEmailUsed(u.Email)
  472. if err != nil {
  473. return err
  474. } else if isExist {
  475. return ErrEmailAlreadyUsed{u.Email}
  476. }
  477. u.LowerName = strings.ToLower(u.Name)
  478. u.AvatarEmail = u.Email
  479. u.Avatar = tool.HashEmail(u.AvatarEmail)
  480. if u.Rands, err = GetUserSalt(); err != nil {
  481. return err
  482. }
  483. if u.Salt, err = GetUserSalt(); err != nil {
  484. return err
  485. }
  486. u.EncodePasswd()
  487. u.MaxRepoCreation = -1
  488. sess := x.NewSession()
  489. defer sess.Close()
  490. if err = sess.Begin(); err != nil {
  491. return err
  492. }
  493. if _, err = sess.Insert(u); err != nil {
  494. return err
  495. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  496. return err
  497. }
  498. return sess.Commit()
  499. }
  500. func countUsers(e Engine) int64 {
  501. count, _ := e.Where("type=0").Count(new(User))
  502. return count
  503. }
  504. // CountUsers returns number of users.
  505. func CountUsers() int64 {
  506. return countUsers(x)
  507. }
  508. // Users returns number of users in given page.
  509. func Users(page, pageSize int) ([]*User, error) {
  510. users := make([]*User, 0, pageSize)
  511. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  512. }
  513. // parseUserFromCode returns user by username encoded in code.
  514. // It returns nil if code or username is invalid.
  515. func parseUserFromCode(code string) (user *User) {
  516. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  517. return nil
  518. }
  519. // Use tail hex username to query user
  520. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  521. if b, err := hex.DecodeString(hexStr); err == nil {
  522. if user, err = GetUserByName(string(b)); user != nil {
  523. return user
  524. } else if !errors.IsUserNotExist(err) {
  525. log.Error(2, "GetUserByName: %v", err)
  526. }
  527. }
  528. return nil
  529. }
  530. // verify active code when active account
  531. func VerifyUserActiveCode(code string) (user *User) {
  532. minutes := setting.Service.ActiveCodeLives
  533. if user = parseUserFromCode(code); user != nil {
  534. // time limit code
  535. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  536. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  537. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  538. return user
  539. }
  540. }
  541. return nil
  542. }
  543. // verify active code when active account
  544. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  545. minutes := setting.Service.ActiveCodeLives
  546. if user := parseUserFromCode(code); user != nil {
  547. // time limit code
  548. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  549. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  550. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  551. emailAddress := &EmailAddress{Email: email}
  552. if has, _ := x.Get(emailAddress); has {
  553. return emailAddress
  554. }
  555. }
  556. }
  557. return nil
  558. }
  559. // ChangeUserName changes all corresponding setting from old user name to new one.
  560. func ChangeUserName(u *User, newUserName string) (err error) {
  561. if err = IsUsableUsername(newUserName); err != nil {
  562. return err
  563. }
  564. isExist, err := IsUserExist(0, newUserName)
  565. if err != nil {
  566. return err
  567. } else if isExist {
  568. return ErrUserAlreadyExist{newUserName}
  569. }
  570. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  571. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  572. }
  573. // Delete all local copies of repository wiki that user owns.
  574. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  575. repo := bean.(*Repository)
  576. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  577. return nil
  578. }); err != nil {
  579. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  580. }
  581. // Rename or create user base directory
  582. baseDir := UserPath(u.Name)
  583. newBaseDir := UserPath(newUserName)
  584. if com.IsExist(baseDir) {
  585. return os.Rename(baseDir, newBaseDir)
  586. }
  587. return os.MkdirAll(newBaseDir, os.ModePerm)
  588. }
  589. func updateUser(e Engine, u *User) error {
  590. // Organization does not need email
  591. if !u.IsOrganization() {
  592. u.Email = strings.ToLower(u.Email)
  593. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  594. if err != nil {
  595. return err
  596. } else if has {
  597. return ErrEmailAlreadyUsed{u.Email}
  598. }
  599. if len(u.AvatarEmail) == 0 {
  600. u.AvatarEmail = u.Email
  601. }
  602. u.Avatar = tool.HashEmail(u.AvatarEmail)
  603. }
  604. u.LowerName = strings.ToLower(u.Name)
  605. u.Location = tool.TruncateString(u.Location, 255)
  606. u.Website = tool.TruncateString(u.Website, 255)
  607. u.Description = tool.TruncateString(u.Description, 255)
  608. _, err := e.Id(u.ID).AllCols().Update(u)
  609. return err
  610. }
  611. // UpdateUser updates user's information.
  612. func UpdateUser(u *User) error {
  613. return updateUser(x, u)
  614. }
  615. // deleteBeans deletes all given beans, beans should contain delete conditions.
  616. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  617. for i := range beans {
  618. if _, err = e.Delete(beans[i]); err != nil {
  619. return err
  620. }
  621. }
  622. return nil
  623. }
  624. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  625. func deleteUser(e *xorm.Session, u *User) error {
  626. // Note: A user owns any repository or belongs to any organization
  627. // cannot perform delete operation.
  628. // Check ownership of repository.
  629. count, err := getRepositoryCount(e, u)
  630. if err != nil {
  631. return fmt.Errorf("GetRepositoryCount: %v", err)
  632. } else if count > 0 {
  633. return ErrUserOwnRepos{UID: u.ID}
  634. }
  635. // Check membership of organization.
  636. count, err = u.getOrganizationCount(e)
  637. if err != nil {
  638. return fmt.Errorf("GetOrganizationCount: %v", err)
  639. } else if count > 0 {
  640. return ErrUserHasOrgs{UID: u.ID}
  641. }
  642. // ***** START: Watch *****
  643. watches := make([]*Watch, 0, 10)
  644. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  645. return fmt.Errorf("get all watches: %v", err)
  646. }
  647. for i := range watches {
  648. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  649. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  650. }
  651. }
  652. // ***** END: Watch *****
  653. // ***** START: Star *****
  654. stars := make([]*Star, 0, 10)
  655. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  656. return fmt.Errorf("get all stars: %v", err)
  657. }
  658. for i := range stars {
  659. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  660. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  661. }
  662. }
  663. // ***** END: Star *****
  664. // ***** START: Follow *****
  665. followers := make([]*Follow, 0, 10)
  666. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  667. return fmt.Errorf("get all followers: %v", err)
  668. }
  669. for i := range followers {
  670. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  671. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  672. }
  673. }
  674. // ***** END: Follow *****
  675. if err = deleteBeans(e,
  676. &AccessToken{UID: u.ID},
  677. &Collaboration{UserID: u.ID},
  678. &Access{UserID: u.ID},
  679. &Watch{UserID: u.ID},
  680. &Star{UID: u.ID},
  681. &Follow{FollowID: u.ID},
  682. &Action{UserID: u.ID},
  683. &IssueUser{UID: u.ID},
  684. &EmailAddress{UID: u.ID},
  685. ); err != nil {
  686. return fmt.Errorf("deleteBeans: %v", err)
  687. }
  688. // ***** START: PublicKey *****
  689. keys := make([]*PublicKey, 0, 10)
  690. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  691. return fmt.Errorf("get all public keys: %v", err)
  692. }
  693. keyIDs := make([]int64, len(keys))
  694. for i := range keys {
  695. keyIDs[i] = keys[i].ID
  696. }
  697. if err = deletePublicKeys(e, keyIDs...); err != nil {
  698. return fmt.Errorf("deletePublicKeys: %v", err)
  699. }
  700. // ***** END: PublicKey *****
  701. // Clear assignee.
  702. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  703. return fmt.Errorf("clear assignee: %v", err)
  704. }
  705. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  706. return fmt.Errorf("Delete: %v", err)
  707. }
  708. // FIXME: system notice
  709. // Note: There are something just cannot be roll back,
  710. // so just keep error logs of those operations.
  711. os.RemoveAll(UserPath(u.Name))
  712. os.Remove(u.CustomAvatarPath())
  713. return nil
  714. }
  715. // DeleteUser completely and permanently deletes everything of a user,
  716. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  717. func DeleteUser(u *User) (err error) {
  718. sess := x.NewSession()
  719. defer sess.Close()
  720. if err = sess.Begin(); err != nil {
  721. return err
  722. }
  723. if err = deleteUser(sess, u); err != nil {
  724. // Note: don't wrapper error here.
  725. return err
  726. }
  727. if err = sess.Commit(); err != nil {
  728. return err
  729. }
  730. return RewriteAllPublicKeys()
  731. }
  732. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  733. func DeleteInactivateUsers() (err error) {
  734. users := make([]*User, 0, 10)
  735. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  736. return fmt.Errorf("get all inactive users: %v", err)
  737. }
  738. // FIXME: should only update authorized_keys file once after all deletions.
  739. for _, u := range users {
  740. if err = DeleteUser(u); err != nil {
  741. // Ignore users that were set inactive by admin.
  742. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  743. continue
  744. }
  745. return err
  746. }
  747. }
  748. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  749. return err
  750. }
  751. // UserPath returns the path absolute path of user repositories.
  752. func UserPath(userName string) string {
  753. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  754. }
  755. func GetUserByKeyID(keyID int64) (*User, error) {
  756. user := new(User)
  757. has, err := x.SQL("SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?", keyID).Get(user)
  758. if err != nil {
  759. return nil, err
  760. } else if !has {
  761. return nil, errors.UserNotKeyOwner{keyID}
  762. }
  763. return user, nil
  764. }
  765. func getUserByID(e Engine, id int64) (*User, error) {
  766. u := new(User)
  767. has, err := e.Id(id).Get(u)
  768. if err != nil {
  769. return nil, err
  770. } else if !has {
  771. return nil, errors.UserNotExist{id, ""}
  772. }
  773. return u, nil
  774. }
  775. // GetUserByID returns the user object by given ID if exists.
  776. func GetUserByID(id int64) (*User, error) {
  777. return getUserByID(x, id)
  778. }
  779. // GetAssigneeByID returns the user with write access of repository by given ID.
  780. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  781. has, err := HasAccess(userID, repo, ACCESS_MODE_READ)
  782. if err != nil {
  783. return nil, err
  784. } else if !has {
  785. return nil, errors.UserNotExist{userID, ""}
  786. }
  787. return GetUserByID(userID)
  788. }
  789. // GetUserByName returns a user by given name.
  790. func GetUserByName(name string) (*User, error) {
  791. if len(name) == 0 {
  792. return nil, errors.UserNotExist{0, name}
  793. }
  794. u := &User{LowerName: strings.ToLower(name)}
  795. has, err := x.Get(u)
  796. if err != nil {
  797. return nil, err
  798. } else if !has {
  799. return nil, errors.UserNotExist{0, name}
  800. }
  801. return u, nil
  802. }
  803. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  804. func GetUserEmailsByNames(names []string) []string {
  805. mails := make([]string, 0, len(names))
  806. for _, name := range names {
  807. u, err := GetUserByName(name)
  808. if err != nil {
  809. continue
  810. }
  811. if u.IsMailable() {
  812. mails = append(mails, u.Email)
  813. }
  814. }
  815. return mails
  816. }
  817. // GetUserIDsByNames returns a slice of ids corresponds to names.
  818. func GetUserIDsByNames(names []string) []int64 {
  819. ids := make([]int64, 0, len(names))
  820. for _, name := range names {
  821. u, err := GetUserByName(name)
  822. if err != nil {
  823. continue
  824. }
  825. ids = append(ids, u.ID)
  826. }
  827. return ids
  828. }
  829. // UserCommit represents a commit with validation of user.
  830. type UserCommit struct {
  831. User *User
  832. *git.Commit
  833. }
  834. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  835. func ValidateCommitWithEmail(c *git.Commit) *User {
  836. u, err := GetUserByEmail(c.Author.Email)
  837. if err != nil {
  838. return nil
  839. }
  840. return u
  841. }
  842. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  843. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  844. var (
  845. u *User
  846. emails = map[string]*User{}
  847. newCommits = list.New()
  848. e = oldCommits.Front()
  849. )
  850. for e != nil {
  851. c := e.Value.(*git.Commit)
  852. if v, ok := emails[c.Author.Email]; !ok {
  853. u, _ = GetUserByEmail(c.Author.Email)
  854. emails[c.Author.Email] = u
  855. } else {
  856. u = v
  857. }
  858. newCommits.PushBack(UserCommit{
  859. User: u,
  860. Commit: c,
  861. })
  862. e = e.Next()
  863. }
  864. return newCommits
  865. }
  866. // GetUserByEmail returns the user object by given e-mail if exists.
  867. func GetUserByEmail(email string) (*User, error) {
  868. if len(email) == 0 {
  869. return nil, errors.UserNotExist{0, "email"}
  870. }
  871. email = strings.ToLower(email)
  872. // First try to find the user by primary email
  873. user := &User{Email: email}
  874. has, err := x.Get(user)
  875. if err != nil {
  876. return nil, err
  877. }
  878. if has {
  879. return user, nil
  880. }
  881. // Otherwise, check in alternative list for activated email addresses
  882. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  883. has, err = x.Get(emailAddress)
  884. if err != nil {
  885. return nil, err
  886. }
  887. if has {
  888. return GetUserByID(emailAddress.UID)
  889. }
  890. return nil, errors.UserNotExist{0, email}
  891. }
  892. type SearchUserOptions struct {
  893. Keyword string
  894. Type UserType
  895. OrderBy string
  896. Page int
  897. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  898. }
  899. // SearchUserByName takes keyword and part of user name to search,
  900. // it returns results in given range and number of total results.
  901. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  902. if len(opts.Keyword) == 0 {
  903. return users, 0, nil
  904. }
  905. opts.Keyword = strings.ToLower(opts.Keyword)
  906. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  907. opts.PageSize = setting.UI.ExplorePagingNum
  908. }
  909. if opts.Page <= 0 {
  910. opts.Page = 1
  911. }
  912. searchQuery := "%" + opts.Keyword + "%"
  913. users = make([]*User, 0, opts.PageSize)
  914. // Append conditions
  915. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  916. Or("LOWER(full_name) LIKE ?", searchQuery).
  917. And("type = ?", opts.Type)
  918. var countSess xorm.Session
  919. countSess = *sess
  920. count, err := countSess.Count(new(User))
  921. if err != nil {
  922. return nil, 0, fmt.Errorf("Count: %v", err)
  923. }
  924. if len(opts.OrderBy) > 0 {
  925. sess.OrderBy(opts.OrderBy)
  926. }
  927. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  928. }
  929. // ___________ .__ .__
  930. // \_ _____/___ | | | | ______ _ __
  931. // | __)/ _ \| | | | / _ \ \/ \/ /
  932. // | \( <_> ) |_| |_( <_> ) /
  933. // \___ / \____/|____/____/\____/ \/\_/
  934. // \/
  935. // Follow represents relations of user and his/her followers.
  936. type Follow struct {
  937. ID int64
  938. UserID int64 `xorm:"UNIQUE(follow)"`
  939. FollowID int64 `xorm:"UNIQUE(follow)"`
  940. }
  941. func IsFollowing(userID, followID int64) bool {
  942. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  943. return has
  944. }
  945. // FollowUser marks someone be another's follower.
  946. func FollowUser(userID, followID int64) (err error) {
  947. if userID == followID || IsFollowing(userID, followID) {
  948. return nil
  949. }
  950. sess := x.NewSession()
  951. defer sess.Close()
  952. if err = sess.Begin(); err != nil {
  953. return err
  954. }
  955. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  956. return err
  957. }
  958. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  959. return err
  960. }
  961. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  962. return err
  963. }
  964. return sess.Commit()
  965. }
  966. // UnfollowUser unmarks someone be another's follower.
  967. func UnfollowUser(userID, followID int64) (err error) {
  968. if userID == followID || !IsFollowing(userID, followID) {
  969. return nil
  970. }
  971. sess := x.NewSession()
  972. defer sess.Close()
  973. if err = sess.Begin(); err != nil {
  974. return err
  975. }
  976. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  977. return err
  978. }
  979. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  980. return err
  981. }
  982. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  983. return err
  984. }
  985. return sess.Commit()
  986. }