user.go 30 KB

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