user.go 30 KB

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