user.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152
  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 `xorm:"pk autoincr"`
  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 sessionRelease(sess)
  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 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{"assets", "css", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", "..","*.about","*.outages","*.tos","*.fingerprints"}
  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 sessionRelease(sess)
  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. // get user by erify code
  514. func getVerifyUser(code string) (user *User) {
  515. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  516. return nil
  517. }
  518. // use tail hex username query user
  519. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  520. if b, err := hex.DecodeString(hexStr); err == nil {
  521. if user, err = GetUserByName(string(b)); user != nil {
  522. return user
  523. } else if !errors.IsUserNotExist(err) {
  524. log.Error(2, "GetUserByName: %v", err)
  525. }
  526. }
  527. return nil
  528. }
  529. // verify active code when active account
  530. func VerifyUserActiveCode(code string) (user *User) {
  531. minutes := setting.Service.ActiveCodeLives
  532. if user = getVerifyUser(code); user != nil {
  533. // time limit code
  534. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  535. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  536. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  537. return user
  538. }
  539. }
  540. return nil
  541. }
  542. // verify active code when active account
  543. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  544. minutes := setting.Service.ActiveCodeLives
  545. if user := getVerifyUser(code); user != nil {
  546. // time limit code
  547. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  548. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  549. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  550. emailAddress := &EmailAddress{Email: email}
  551. if has, _ := x.Get(emailAddress); has {
  552. return emailAddress
  553. }
  554. }
  555. }
  556. return nil
  557. }
  558. // ChangeUserName changes all corresponding setting from old user name to new one.
  559. func ChangeUserName(u *User, newUserName string) (err error) {
  560. if err = IsUsableUsername(newUserName); err != nil {
  561. return err
  562. }
  563. isExist, err := IsUserExist(0, newUserName)
  564. if err != nil {
  565. return err
  566. } else if isExist {
  567. return ErrUserAlreadyExist{newUserName}
  568. }
  569. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  570. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  571. }
  572. // Delete all local copies of repository wiki that user owns.
  573. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  574. repo := bean.(*Repository)
  575. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  576. return nil
  577. }); err != nil {
  578. return fmt.Errorf("Delete repository wiki local copy: %v", err)
  579. }
  580. // Rename or create user base directory
  581. baseDir := UserPath(u.Name)
  582. newBaseDir := UserPath(newUserName)
  583. if com.IsExist(baseDir) {
  584. return os.Rename(baseDir, newBaseDir)
  585. }
  586. return os.MkdirAll(newBaseDir, os.ModePerm)
  587. }
  588. func updateUser(e Engine, u *User) error {
  589. // Organization does not need email
  590. if !u.IsOrganization() {
  591. u.Email = strings.ToLower(u.Email)
  592. has, err := e.Where("id!=?", u.ID).And("type=?", u.Type).And("email=?", u.Email).Get(new(User))
  593. if err != nil {
  594. return err
  595. } else if has {
  596. return ErrEmailAlreadyUsed{u.Email}
  597. }
  598. if len(u.AvatarEmail) == 0 {
  599. u.AvatarEmail = u.Email
  600. }
  601. u.Avatar = tool.HashEmail(u.AvatarEmail)
  602. }
  603. u.LowerName = strings.ToLower(u.Name)
  604. u.Location = tool.TruncateString(u.Location, 255)
  605. u.Website = tool.TruncateString(u.Website, 255)
  606. u.Description = tool.TruncateString(u.Description, 255)
  607. _, err := e.Id(u.ID).AllCols().Update(u)
  608. return err
  609. }
  610. // UpdateUser updates user's information.
  611. func UpdateUser(u *User) error {
  612. return updateUser(x, u)
  613. }
  614. // deleteBeans deletes all given beans, beans should contain delete conditions.
  615. func deleteBeans(e Engine, beans ...interface{}) (err error) {
  616. for i := range beans {
  617. if _, err = e.Delete(beans[i]); err != nil {
  618. return err
  619. }
  620. }
  621. return nil
  622. }
  623. // FIXME: need some kind of mechanism to record failure. HINT: system notice
  624. func deleteUser(e *xorm.Session, u *User) error {
  625. // Note: A user owns any repository or belongs to any organization
  626. // cannot perform delete operation.
  627. // Check ownership of repository.
  628. count, err := getRepositoryCount(e, u)
  629. if err != nil {
  630. return fmt.Errorf("GetRepositoryCount: %v", err)
  631. } else if count > 0 {
  632. return ErrUserOwnRepos{UID: u.ID}
  633. }
  634. // Check membership of organization.
  635. count, err = u.getOrganizationCount(e)
  636. if err != nil {
  637. return fmt.Errorf("GetOrganizationCount: %v", err)
  638. } else if count > 0 {
  639. return ErrUserHasOrgs{UID: u.ID}
  640. }
  641. // ***** START: Watch *****
  642. watches := make([]*Watch, 0, 10)
  643. if err = e.Find(&watches, &Watch{UserID: u.ID}); err != nil {
  644. return fmt.Errorf("get all watches: %v", err)
  645. }
  646. for i := range watches {
  647. if _, err = e.Exec("UPDATE `repository` SET num_watches=num_watches-1 WHERE id=?", watches[i].RepoID); err != nil {
  648. return fmt.Errorf("decrease repository watch number[%d]: %v", watches[i].RepoID, err)
  649. }
  650. }
  651. // ***** END: Watch *****
  652. // ***** START: Star *****
  653. stars := make([]*Star, 0, 10)
  654. if err = e.Find(&stars, &Star{UID: u.ID}); err != nil {
  655. return fmt.Errorf("get all stars: %v", err)
  656. }
  657. for i := range stars {
  658. if _, err = e.Exec("UPDATE `repository` SET num_stars=num_stars-1 WHERE id=?", stars[i].RepoID); err != nil {
  659. return fmt.Errorf("decrease repository star number[%d]: %v", stars[i].RepoID, err)
  660. }
  661. }
  662. // ***** END: Star *****
  663. // ***** START: Follow *****
  664. followers := make([]*Follow, 0, 10)
  665. if err = e.Find(&followers, &Follow{UserID: u.ID}); err != nil {
  666. return fmt.Errorf("get all followers: %v", err)
  667. }
  668. for i := range followers {
  669. if _, err = e.Exec("UPDATE `user` SET num_followers=num_followers-1 WHERE id=?", followers[i].UserID); err != nil {
  670. return fmt.Errorf("decrease user follower number[%d]: %v", followers[i].UserID, err)
  671. }
  672. }
  673. // ***** END: Follow *****
  674. if err = deleteBeans(e,
  675. &AccessToken{UID: u.ID},
  676. &Collaboration{UserID: u.ID},
  677. &Access{UserID: u.ID},
  678. &Watch{UserID: u.ID},
  679. &Star{UID: u.ID},
  680. &Follow{FollowID: u.ID},
  681. &Action{UserID: u.ID},
  682. &IssueUser{UID: u.ID},
  683. &EmailAddress{UID: u.ID},
  684. ); err != nil {
  685. return fmt.Errorf("deleteBeans: %v", err)
  686. }
  687. // ***** START: PublicKey *****
  688. keys := make([]*PublicKey, 0, 10)
  689. if err = e.Find(&keys, &PublicKey{OwnerID: u.ID}); err != nil {
  690. return fmt.Errorf("get all public keys: %v", err)
  691. }
  692. keyIDs := make([]int64, len(keys))
  693. for i := range keys {
  694. keyIDs[i] = keys[i].ID
  695. }
  696. if err = deletePublicKeys(e, keyIDs...); err != nil {
  697. return fmt.Errorf("deletePublicKeys: %v", err)
  698. }
  699. // ***** END: PublicKey *****
  700. // Clear assignee.
  701. if _, err = e.Exec("UPDATE `issue` SET assignee_id=0 WHERE assignee_id=?", u.ID); err != nil {
  702. return fmt.Errorf("clear assignee: %v", err)
  703. }
  704. if _, err = e.Id(u.ID).Delete(new(User)); err != nil {
  705. return fmt.Errorf("Delete: %v", err)
  706. }
  707. // FIXME: system notice
  708. // Note: There are something just cannot be roll back,
  709. // so just keep error logs of those operations.
  710. os.RemoveAll(UserPath(u.Name))
  711. os.Remove(u.CustomAvatarPath())
  712. return nil
  713. }
  714. // DeleteUser completely and permanently deletes everything of a user,
  715. // but issues/comments/pulls will be kept and shown as someone has been deleted.
  716. func DeleteUser(u *User) (err error) {
  717. sess := x.NewSession()
  718. defer sessionRelease(sess)
  719. if err = sess.Begin(); err != nil {
  720. return err
  721. }
  722. if err = deleteUser(sess, u); err != nil {
  723. // Note: don't wrapper error here.
  724. return err
  725. }
  726. if err = sess.Commit(); err != nil {
  727. return err
  728. }
  729. return RewriteAllPublicKeys()
  730. }
  731. // DeleteInactivateUsers deletes all inactivate users and email addresses.
  732. func DeleteInactivateUsers() (err error) {
  733. users := make([]*User, 0, 10)
  734. if err = x.Where("is_active = ?", false).Find(&users); err != nil {
  735. return fmt.Errorf("get all inactive users: %v", err)
  736. }
  737. // FIXME: should only update authorized_keys file once after all deletions.
  738. for _, u := range users {
  739. if err = DeleteUser(u); err != nil {
  740. // Ignore users that were set inactive by admin.
  741. if IsErrUserOwnRepos(err) || IsErrUserHasOrgs(err) {
  742. continue
  743. }
  744. return err
  745. }
  746. }
  747. _, err = x.Where("is_activated = ?", false).Delete(new(EmailAddress))
  748. return err
  749. }
  750. // UserPath returns the path absolute path of user repositories.
  751. func UserPath(userName string) string {
  752. return filepath.Join(setting.RepoRootPath, strings.ToLower(userName))
  753. }
  754. func GetUserByKeyID(keyID int64) (*User, error) {
  755. user := new(User)
  756. 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)
  757. if err != nil {
  758. return nil, err
  759. } else if !has {
  760. return nil, errors.UserNotKeyOwner{keyID}
  761. }
  762. return user, nil
  763. }
  764. func getUserByID(e Engine, id int64) (*User, error) {
  765. u := new(User)
  766. has, err := e.Id(id).Get(u)
  767. if err != nil {
  768. return nil, err
  769. } else if !has {
  770. return nil, errors.UserNotExist{id, ""}
  771. }
  772. return u, nil
  773. }
  774. // GetUserByID returns the user object by given ID if exists.
  775. func GetUserByID(id int64) (*User, error) {
  776. return getUserByID(x, id)
  777. }
  778. // GetAssigneeByID returns the user with write access of repository by given ID.
  779. func GetAssigneeByID(repo *Repository, userID int64) (*User, error) {
  780. has, err := HasAccess(userID, repo, ACCESS_MODE_READ)
  781. if err != nil {
  782. return nil, err
  783. } else if !has {
  784. return nil, errors.UserNotExist{userID, ""}
  785. }
  786. return GetUserByID(userID)
  787. }
  788. // GetUserByName returns user by given name.
  789. func GetUserByName(name string) (*User, error) {
  790. if len(name) == 0 {
  791. return nil, errors.UserNotExist{0, name}
  792. }
  793. u := &User{LowerName: strings.ToLower(name)}
  794. has, err := x.Get(u)
  795. if err != nil {
  796. return nil, err
  797. } else if !has {
  798. return nil, errors.UserNotExist{0, name}
  799. }
  800. return u, nil
  801. }
  802. // GetUserEmailsByNames returns a list of e-mails corresponds to names.
  803. func GetUserEmailsByNames(names []string) []string {
  804. mails := make([]string, 0, len(names))
  805. for _, name := range names {
  806. u, err := GetUserByName(name)
  807. if err != nil {
  808. continue
  809. }
  810. if u.IsMailable() {
  811. mails = append(mails, u.Email)
  812. }
  813. }
  814. return mails
  815. }
  816. // GetUserIDsByNames returns a slice of ids corresponds to names.
  817. func GetUserIDsByNames(names []string) []int64 {
  818. ids := make([]int64, 0, len(names))
  819. for _, name := range names {
  820. u, err := GetUserByName(name)
  821. if err != nil {
  822. continue
  823. }
  824. ids = append(ids, u.ID)
  825. }
  826. return ids
  827. }
  828. // UserCommit represents a commit with validation of user.
  829. type UserCommit struct {
  830. User *User
  831. *git.Commit
  832. }
  833. // ValidateCommitWithEmail chceck if author's e-mail of commit is corresponsind to a user.
  834. func ValidateCommitWithEmail(c *git.Commit) *User {
  835. u, err := GetUserByEmail(c.Author.Email)
  836. if err != nil {
  837. return nil
  838. }
  839. return u
  840. }
  841. // ValidateCommitsWithEmails checks if authors' e-mails of commits are corresponding to users.
  842. func ValidateCommitsWithEmails(oldCommits *list.List) *list.List {
  843. var (
  844. u *User
  845. emails = map[string]*User{}
  846. newCommits = list.New()
  847. e = oldCommits.Front()
  848. )
  849. for e != nil {
  850. c := e.Value.(*git.Commit)
  851. if v, ok := emails[c.Author.Email]; !ok {
  852. u, _ = GetUserByEmail(c.Author.Email)
  853. emails[c.Author.Email] = u
  854. } else {
  855. u = v
  856. }
  857. newCommits.PushBack(UserCommit{
  858. User: u,
  859. Commit: c,
  860. })
  861. e = e.Next()
  862. }
  863. return newCommits
  864. }
  865. // GetUserByEmail returns the user object by given e-mail if exists.
  866. func GetUserByEmail(email string) (*User, error) {
  867. if len(email) == 0 {
  868. return nil, errors.UserNotExist{0, "email"}
  869. }
  870. email = strings.ToLower(email)
  871. // First try to find the user by primary email
  872. user := &User{Email: email}
  873. has, err := x.Get(user)
  874. if err != nil {
  875. return nil, err
  876. }
  877. if has {
  878. return user, nil
  879. }
  880. // Otherwise, check in alternative list for activated email addresses
  881. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  882. has, err = x.Get(emailAddress)
  883. if err != nil {
  884. return nil, err
  885. }
  886. if has {
  887. return GetUserByID(emailAddress.UID)
  888. }
  889. return nil, errors.UserNotExist{0, email}
  890. }
  891. type SearchUserOptions struct {
  892. Keyword string
  893. Type UserType
  894. OrderBy string
  895. Page int
  896. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  897. }
  898. // SearchUserByName takes keyword and part of user name to search,
  899. // it returns results in given range and number of total results.
  900. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  901. if len(opts.Keyword) == 0 {
  902. return users, 0, nil
  903. }
  904. opts.Keyword = strings.ToLower(opts.Keyword)
  905. if opts.PageSize <= 0 || opts.PageSize > setting.UI.ExplorePagingNum {
  906. opts.PageSize = setting.UI.ExplorePagingNum
  907. }
  908. if opts.Page <= 0 {
  909. opts.Page = 1
  910. }
  911. searchQuery := "%" + opts.Keyword + "%"
  912. users = make([]*User, 0, opts.PageSize)
  913. // Append conditions
  914. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  915. Or("LOWER(full_name) LIKE ?", searchQuery).
  916. And("type = ?", opts.Type)
  917. var countSess xorm.Session
  918. countSess = *sess
  919. count, err := countSess.Count(new(User))
  920. if err != nil {
  921. return nil, 0, fmt.Errorf("Count: %v", err)
  922. }
  923. if len(opts.OrderBy) > 0 {
  924. sess.OrderBy(opts.OrderBy)
  925. }
  926. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  927. }
  928. // ___________ .__ .__
  929. // \_ _____/___ | | | | ______ _ __
  930. // | __)/ _ \| | | | / _ \ \/ \/ /
  931. // | \( <_> ) |_| |_( <_> ) /
  932. // \___ / \____/|____/____/\____/ \/\_/
  933. // \/
  934. // Follow represents relations of user and his/her followers.
  935. type Follow struct {
  936. ID int64 `xorm:"pk autoincr"`
  937. UserID int64 `xorm:"UNIQUE(follow)"`
  938. FollowID int64 `xorm:"UNIQUE(follow)"`
  939. }
  940. func IsFollowing(userID, followID int64) bool {
  941. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  942. return has
  943. }
  944. // FollowUser marks someone be another's follower.
  945. func FollowUser(userID, followID int64) (err error) {
  946. if userID == followID || IsFollowing(userID, followID) {
  947. return nil
  948. }
  949. sess := x.NewSession()
  950. defer sessionRelease(sess)
  951. if err = sess.Begin(); err != nil {
  952. return err
  953. }
  954. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  955. return err
  956. }
  957. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  958. return err
  959. }
  960. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  961. return err
  962. }
  963. return sess.Commit()
  964. }
  965. // UnfollowUser unmarks someone be another's follower.
  966. func UnfollowUser(userID, followID int64) (err error) {
  967. if userID == followID || !IsFollowing(userID, followID) {
  968. return nil
  969. }
  970. sess := x.NewSession()
  971. defer sessionRelease(sess)
  972. if err = sess.Begin(); err != nil {
  973. return err
  974. }
  975. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  976. return err
  977. }
  978. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  979. return err
  980. }
  981. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  982. return err
  983. }
  984. return sess.Commit()
  985. }