You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.go 30 kB

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