user.go 30 KB

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