user.go 30 KB

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