user.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141
  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 db
  5. import (
  6. "bytes"
  7. "crypto/sha256"
  8. "crypto/subtle"
  9. "encoding/hex"
  10. "fmt"
  11. "image"
  12. _ "image/jpeg"
  13. "image/png"
  14. "os"
  15. "path/filepath"
  16. "strings"
  17. "time"
  18. "unicode/utf8"
  19. "github.com/nfnt/resize"
  20. "github.com/unknwon/com"
  21. "golang.org/x/crypto/pbkdf2"
  22. log "unknwon.dev/clog/v2"
  23. "xorm.io/xorm"
  24. "github.com/gogs/git-module"
  25. api "github.com/gogs/go-gogs-client"
  26. "gogs.io/gogs/internal/avatar"
  27. "gogs.io/gogs/internal/conf"
  28. "gogs.io/gogs/internal/db/errors"
  29. "gogs.io/gogs/internal/tool"
  30. )
  31. // USER_AVATAR_URL_PREFIX is used to identify a URL is to access user avatar.
  32. const USER_AVATAR_URL_PREFIX = "avatars"
  33. type UserType int
  34. const (
  35. USER_TYPE_INDIVIDUAL UserType = iota // Historic reason to make it starts at 0.
  36. USER_TYPE_ORGANIZATION
  37. )
  38. // User represents the object of individual and member of organization.
  39. type User struct {
  40. ID int64
  41. LowerName string `xorm:"UNIQUE NOT NULL"`
  42. Name string `xorm:"UNIQUE NOT NULL"`
  43. FullName string
  44. // Email is the primary email address (to be used for communication)
  45. Email string `xorm:"NOT NULL"`
  46. Passwd string `xorm:"NOT NULL"`
  47. LoginType LoginType
  48. LoginSource int64 `xorm:"NOT NULL DEFAULT 0"`
  49. LoginName string
  50. Type UserType
  51. OwnedOrgs []*User `xorm:"-" json:"-"`
  52. Orgs []*User `xorm:"-" json:"-"`
  53. Repos []*Repository `xorm:"-" json:"-"`
  54. Location string
  55. Website string
  56. Rands string `xorm:"VARCHAR(10)"`
  57. Salt string `xorm:"VARCHAR(10)"`
  58. Created time.Time `xorm:"-" json:"-"`
  59. CreatedUnix int64
  60. Updated time.Time `xorm:"-" json:"-"`
  61. UpdatedUnix int64
  62. // Remember visibility choice for convenience, true for private
  63. LastRepoVisibility bool
  64. // Maximum repository creation limit, -1 means use gloabl default
  65. MaxRepoCreation int `xorm:"NOT NULL DEFAULT -1"`
  66. // Permissions
  67. IsActive bool // Activate primary email
  68. IsAdmin bool
  69. AllowGitHook bool
  70. AllowImportLocal bool // Allow migrate repository by local path
  71. ProhibitLogin bool
  72. // Avatar
  73. Avatar string `xorm:"VARCHAR(2048) NOT NULL"`
  74. AvatarEmail string `xorm:"NOT NULL"`
  75. UseCustomAvatar bool
  76. // Counters
  77. NumFollowers int
  78. NumFollowing int `xorm:"NOT NULL DEFAULT 0"`
  79. NumStars int
  80. NumRepos int
  81. // For organization
  82. Description string
  83. NumTeams int
  84. NumMembers int
  85. Teams []*Team `xorm:"-" json:"-"`
  86. Members []*User `xorm:"-" json:"-"`
  87. }
  88. func (u *User) BeforeInsert() {
  89. u.CreatedUnix = time.Now().Unix()
  90. u.UpdatedUnix = u.CreatedUnix
  91. }
  92. func (u *User) BeforeUpdate() {
  93. if u.MaxRepoCreation < -1 {
  94. u.MaxRepoCreation = -1
  95. }
  96. u.UpdatedUnix = time.Now().Unix()
  97. }
  98. func (u *User) AfterSet(colName string, _ xorm.Cell) {
  99. switch colName {
  100. case "created_unix":
  101. u.Created = time.Unix(u.CreatedUnix, 0).Local()
  102. case "updated_unix":
  103. u.Updated = time.Unix(u.UpdatedUnix, 0).Local()
  104. }
  105. }
  106. // IDStr returns string representation of user's ID.
  107. func (u *User) IDStr() string {
  108. return com.ToStr(u.ID)
  109. }
  110. func (u *User) APIFormat() *api.User {
  111. return &api.User{
  112. ID: u.ID,
  113. UserName: u.Name,
  114. Login: u.Name,
  115. FullName: u.FullName,
  116. Email: u.Email,
  117. AvatarUrl: u.AvatarLink(),
  118. }
  119. }
  120. // returns true if user login type is LOGIN_PLAIN.
  121. func (u *User) IsLocal() bool {
  122. return u.LoginType <= LOGIN_PLAIN
  123. }
  124. // HasForkedRepo checks if user has already forked a repository with given ID.
  125. func (u *User) HasForkedRepo(repoID int64) bool {
  126. _, has, _ := HasForkedRepo(u.ID, repoID)
  127. return has
  128. }
  129. func (u *User) RepoCreationNum() int {
  130. if u.MaxRepoCreation <= -1 {
  131. return conf.Repository.MaxCreationLimit
  132. }
  133. return u.MaxRepoCreation
  134. }
  135. func (u *User) CanCreateRepo() bool {
  136. if u.MaxRepoCreation <= -1 {
  137. if conf.Repository.MaxCreationLimit <= -1 {
  138. return true
  139. }
  140. return u.NumRepos < conf.Repository.MaxCreationLimit
  141. }
  142. return u.NumRepos < u.MaxRepoCreation
  143. }
  144. func (u *User) CanCreateOrganization() bool {
  145. return !conf.Admin.DisableRegularOrgCreation || u.IsAdmin
  146. }
  147. // CanEditGitHook returns true if user can edit Git hooks.
  148. func (u *User) CanEditGitHook() bool {
  149. return u.IsAdmin || u.AllowGitHook
  150. }
  151. // CanImportLocal returns true if user can migrate repository by local path.
  152. func (u *User) CanImportLocal() bool {
  153. return conf.Repository.EnableLocalPathMigration && (u.IsAdmin || u.AllowImportLocal)
  154. }
  155. // DashboardLink returns the user dashboard page link.
  156. func (u *User) DashboardLink() string {
  157. if u.IsOrganization() {
  158. return conf.Server.Subpath + "/org/" + u.Name + "/dashboard/"
  159. }
  160. return conf.Server.Subpath + "/"
  161. }
  162. // HomeLink returns the user or organization home page link.
  163. func (u *User) HomeLink() string {
  164. return conf.Server.Subpath + "/" + u.Name
  165. }
  166. func (u *User) HTMLURL() string {
  167. return conf.Server.ExternalURL + u.Name
  168. }
  169. // GenerateEmailActivateCode generates an activate code based on user information and given e-mail.
  170. func (u *User) GenerateEmailActivateCode(email string) string {
  171. code := tool.CreateTimeLimitCode(
  172. com.ToStr(u.ID)+email+u.LowerName+u.Passwd+u.Rands,
  173. conf.Auth.ActivateCodeLives, nil)
  174. // Add tail hex username
  175. code += hex.EncodeToString([]byte(u.LowerName))
  176. return code
  177. }
  178. // GenerateActivateCode generates an activate code based on user information.
  179. func (u *User) GenerateActivateCode() string {
  180. return u.GenerateEmailActivateCode(u.Email)
  181. }
  182. // CustomAvatarPath returns user custom avatar file path.
  183. func (u *User) CustomAvatarPath() string {
  184. return filepath.Join(conf.Picture.AvatarUploadPath, com.ToStr(u.ID))
  185. }
  186. // GenerateRandomAvatar generates a random avatar for user.
  187. func (u *User) GenerateRandomAvatar() error {
  188. seed := u.Email
  189. if len(seed) == 0 {
  190. seed = u.Name
  191. }
  192. img, err := avatar.RandomImage([]byte(seed))
  193. if err != nil {
  194. return fmt.Errorf("RandomImage: %v", err)
  195. }
  196. if err = os.MkdirAll(filepath.Dir(u.CustomAvatarPath()), os.ModePerm); err != nil {
  197. return fmt.Errorf("MkdirAll: %v", err)
  198. }
  199. fw, err := os.Create(u.CustomAvatarPath())
  200. if err != nil {
  201. return fmt.Errorf("Create: %v", err)
  202. }
  203. defer fw.Close()
  204. if err = png.Encode(fw, img); err != nil {
  205. return fmt.Errorf("Encode: %v", err)
  206. }
  207. log.Info("New random avatar created: %d", u.ID)
  208. return nil
  209. }
  210. // RelAvatarLink returns relative avatar link to the site domain,
  211. // which includes app sub-url as prefix. However, it is possible
  212. // to return full URL if user enables Gravatar-like service.
  213. func (u *User) RelAvatarLink() string {
  214. defaultImgUrl := conf.Server.Subpath + "/img/avatar_default.png"
  215. if u.ID == -1 {
  216. return defaultImgUrl
  217. }
  218. switch {
  219. case u.UseCustomAvatar:
  220. if !com.IsExist(u.CustomAvatarPath()) {
  221. return defaultImgUrl
  222. }
  223. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, USER_AVATAR_URL_PREFIX, u.ID)
  224. case conf.Picture.DisableGravatar:
  225. if !com.IsExist(u.CustomAvatarPath()) {
  226. if err := u.GenerateRandomAvatar(); err != nil {
  227. log.Error("GenerateRandomAvatar: %v", err)
  228. }
  229. }
  230. return fmt.Sprintf("%s/%s/%d", conf.Server.Subpath, USER_AVATAR_URL_PREFIX, u.ID)
  231. }
  232. return tool.AvatarLink(u.AvatarEmail)
  233. }
  234. // AvatarLink returns user avatar absolute link.
  235. func (u *User) AvatarLink() string {
  236. link := u.RelAvatarLink()
  237. if link[0] == '/' && link[1] != '/' {
  238. return conf.Server.ExternalURL + strings.TrimPrefix(link, conf.Server.Subpath)[1:]
  239. }
  240. return link
  241. }
  242. // User.GetFollwoers returns range of user's followers.
  243. func (u *User) GetFollowers(page int) ([]*User, error) {
  244. users := make([]*User, 0, ItemsPerPage)
  245. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.follow_id=?", u.ID)
  246. if conf.UsePostgreSQL {
  247. sess = sess.Join("LEFT", "follow", `"user".id=follow.user_id`)
  248. } else {
  249. sess = sess.Join("LEFT", "follow", "user.id=follow.user_id")
  250. }
  251. return users, sess.Find(&users)
  252. }
  253. func (u *User) IsFollowing(followID int64) bool {
  254. return IsFollowing(u.ID, followID)
  255. }
  256. // GetFollowing returns range of user's following.
  257. func (u *User) GetFollowing(page int) ([]*User, error) {
  258. users := make([]*User, 0, ItemsPerPage)
  259. sess := x.Limit(ItemsPerPage, (page-1)*ItemsPerPage).Where("follow.user_id=?", u.ID)
  260. if conf.UsePostgreSQL {
  261. sess = sess.Join("LEFT", "follow", `"user".id=follow.follow_id`)
  262. } else {
  263. sess = sess.Join("LEFT", "follow", "user.id=follow.follow_id")
  264. }
  265. return users, sess.Find(&users)
  266. }
  267. // NewGitSig generates and returns the signature of given user.
  268. func (u *User) NewGitSig() *git.Signature {
  269. return &git.Signature{
  270. Name: u.DisplayName(),
  271. Email: u.Email,
  272. When: time.Now(),
  273. }
  274. }
  275. // EncodePasswd encodes password to safe format.
  276. func (u *User) EncodePasswd() {
  277. newPasswd := pbkdf2.Key([]byte(u.Passwd), []byte(u.Salt), 10000, 50, sha256.New)
  278. u.Passwd = fmt.Sprintf("%x", newPasswd)
  279. }
  280. // ValidatePassword checks if given password matches the one belongs to the user.
  281. func (u *User) ValidatePassword(passwd string) bool {
  282. newUser := &User{Passwd: passwd, Salt: u.Salt}
  283. newUser.EncodePasswd()
  284. return subtle.ConstantTimeCompare([]byte(u.Passwd), []byte(newUser.Passwd)) == 1
  285. }
  286. // UploadAvatar saves custom avatar for user.
  287. // FIXME: split uploads to different subdirs in case we have massive number of users.
  288. func (u *User) UploadAvatar(data []byte) error {
  289. img, _, err := image.Decode(bytes.NewReader(data))
  290. if err != nil {
  291. return fmt.Errorf("decode image: %v", err)
  292. }
  293. _ = os.MkdirAll(conf.Picture.AvatarUploadPath, os.ModePerm)
  294. fw, err := os.Create(u.CustomAvatarPath())
  295. if err != nil {
  296. return fmt.Errorf("create custom avatar directory: %v", err)
  297. }
  298. defer fw.Close()
  299. m := resize.Resize(avatar.AVATAR_SIZE, avatar.AVATAR_SIZE, img, resize.NearestNeighbor)
  300. if err = png.Encode(fw, m); err != nil {
  301. return fmt.Errorf("encode image: %v", err)
  302. }
  303. return nil
  304. }
  305. // DeleteAvatar deletes the user's custom avatar.
  306. func (u *User) DeleteAvatar() error {
  307. log.Trace("DeleteAvatar [%d]: %s", u.ID, u.CustomAvatarPath())
  308. if err := os.Remove(u.CustomAvatarPath()); err != nil {
  309. return err
  310. }
  311. u.UseCustomAvatar = false
  312. return UpdateUser(u)
  313. }
  314. // IsAdminOfRepo returns true if user has admin or higher access of repository.
  315. func (u *User) IsAdminOfRepo(repo *Repository) bool {
  316. has, err := HasAccess(u.ID, repo, ACCESS_MODE_ADMIN)
  317. if err != nil {
  318. log.Error("HasAccess: %v", err)
  319. }
  320. return has
  321. }
  322. // IsWriterOfRepo returns true if user has write access to given repository.
  323. func (u *User) IsWriterOfRepo(repo *Repository) bool {
  324. has, err := HasAccess(u.ID, repo, ACCESS_MODE_WRITE)
  325. if err != nil {
  326. log.Error("HasAccess: %v", err)
  327. }
  328. return has
  329. }
  330. // IsOrganization returns true if user is actually a organization.
  331. func (u *User) IsOrganization() bool {
  332. return u.Type == USER_TYPE_ORGANIZATION
  333. }
  334. // IsUserOrgOwner returns true if user is in the owner team of given organization.
  335. func (u *User) IsUserOrgOwner(orgId int64) bool {
  336. return IsOrganizationOwner(orgId, u.ID)
  337. }
  338. // IsPublicMember returns true if user public his/her membership in give organization.
  339. func (u *User) IsPublicMember(orgId int64) bool {
  340. return IsPublicMembership(orgId, u.ID)
  341. }
  342. // IsEnabledTwoFactor returns true if user has enabled two-factor authentication.
  343. func (u *User) IsEnabledTwoFactor() bool {
  344. return IsUserEnabledTwoFactor(u.ID)
  345. }
  346. func (u *User) getOrganizationCount(e Engine) (int64, error) {
  347. return e.Where("uid=?", u.ID).Count(new(OrgUser))
  348. }
  349. // GetOrganizationCount returns count of membership of organization of user.
  350. func (u *User) GetOrganizationCount() (int64, error) {
  351. return u.getOrganizationCount(x)
  352. }
  353. // GetRepositories returns repositories that user owns, including private repositories.
  354. func (u *User) GetRepositories(page, pageSize int) (err error) {
  355. u.Repos, err = GetUserRepositories(&UserRepoOptions{
  356. UserID: u.ID,
  357. Private: true,
  358. Page: page,
  359. PageSize: pageSize,
  360. })
  361. return err
  362. }
  363. // GetRepositories returns mirror repositories that user owns, including private repositories.
  364. func (u *User) GetMirrorRepositories() ([]*Repository, error) {
  365. return GetUserMirrorRepositories(u.ID)
  366. }
  367. // GetOwnedOrganizations returns all organizations that user owns.
  368. func (u *User) GetOwnedOrganizations() (err error) {
  369. u.OwnedOrgs, err = GetOwnedOrgsByUserID(u.ID)
  370. return err
  371. }
  372. // GetOrganizations returns all organizations that user belongs to.
  373. func (u *User) GetOrganizations(showPrivate bool) error {
  374. orgIDs, err := GetOrgIDsByUserID(u.ID, showPrivate)
  375. if err != nil {
  376. return fmt.Errorf("GetOrgIDsByUserID: %v", err)
  377. }
  378. if len(orgIDs) == 0 {
  379. return nil
  380. }
  381. u.Orgs = make([]*User, 0, len(orgIDs))
  382. if err = x.Where("type = ?", USER_TYPE_ORGANIZATION).In("id", orgIDs).Find(&u.Orgs); err != nil {
  383. return err
  384. }
  385. return nil
  386. }
  387. // DisplayName returns full name if it's not empty,
  388. // returns username otherwise.
  389. func (u *User) DisplayName() string {
  390. if len(u.FullName) > 0 {
  391. return u.FullName
  392. }
  393. return u.Name
  394. }
  395. func (u *User) ShortName(length int) string {
  396. return tool.EllipsisString(u.Name, length)
  397. }
  398. // IsMailable checks if a user is elegible
  399. // to receive emails.
  400. func (u *User) IsMailable() bool {
  401. return u.IsActive
  402. }
  403. // IsUserExist checks if given user name exist,
  404. // the user name should be noncased unique.
  405. // If uid is presented, then check will rule out that one,
  406. // it is used when update a user name in settings page.
  407. func IsUserExist(uid int64, name string) (bool, error) {
  408. if len(name) == 0 {
  409. return false, nil
  410. }
  411. return x.Where("id != ?", uid).Get(&User{LowerName: strings.ToLower(name)})
  412. }
  413. // GetUserSalt returns a ramdom user salt token.
  414. func GetUserSalt() (string, error) {
  415. return tool.RandomString(10)
  416. }
  417. // NewGhostUser creates and returns a fake user for someone who has deleted his/her account.
  418. func NewGhostUser() *User {
  419. return &User{
  420. ID: -1,
  421. Name: "Ghost",
  422. LowerName: "ghost",
  423. }
  424. }
  425. var (
  426. reservedUsernames = []string{"explore", "create", "assets", "css", "img", "js", "less", "plugins", "debug", "raw", "install", "api", "avatar", "user", "org", "help", "stars", "issues", "pulls", "commits", "repo", "template", "admin", "new", ".", ".."}
  427. reservedUserPatterns = []string{"*.keys"}
  428. )
  429. // isUsableName checks if name is reserved or pattern of name is not allowed
  430. // based on given reserved names and patterns.
  431. // Names are exact match, patterns can be prefix or suffix match with placeholder '*'.
  432. func isUsableName(names, patterns []string, name string) error {
  433. name = strings.TrimSpace(strings.ToLower(name))
  434. if utf8.RuneCountInString(name) == 0 {
  435. return errors.EmptyName{}
  436. }
  437. for i := range names {
  438. if name == names[i] {
  439. return ErrNameReserved{name}
  440. }
  441. }
  442. for _, pat := range patterns {
  443. if pat[0] == '*' && strings.HasSuffix(name, pat[1:]) ||
  444. (pat[len(pat)-1] == '*' && strings.HasPrefix(name, pat[:len(pat)-1])) {
  445. return ErrNamePatternNotAllowed{pat}
  446. }
  447. }
  448. return nil
  449. }
  450. func IsUsableUsername(name string) error {
  451. return isUsableName(reservedUsernames, reservedUserPatterns, name)
  452. }
  453. // CreateUser creates record of a new user.
  454. func CreateUser(u *User) (err error) {
  455. if err = IsUsableUsername(u.Name); err != nil {
  456. return err
  457. }
  458. isExist, err := IsUserExist(0, u.Name)
  459. if err != nil {
  460. return err
  461. } else if isExist {
  462. return ErrUserAlreadyExist{u.Name}
  463. }
  464. u.Email = strings.ToLower(u.Email)
  465. isExist, err = IsEmailUsed(u.Email)
  466. if err != nil {
  467. return err
  468. } else if isExist {
  469. return ErrEmailAlreadyUsed{u.Email}
  470. }
  471. u.LowerName = strings.ToLower(u.Name)
  472. u.AvatarEmail = u.Email
  473. u.Avatar = tool.HashEmail(u.AvatarEmail)
  474. if u.Rands, err = GetUserSalt(); err != nil {
  475. return err
  476. }
  477. if u.Salt, err = GetUserSalt(); err != nil {
  478. return err
  479. }
  480. u.EncodePasswd()
  481. u.MaxRepoCreation = -1
  482. sess := x.NewSession()
  483. defer sess.Close()
  484. if err = sess.Begin(); err != nil {
  485. return err
  486. }
  487. if _, err = sess.Insert(u); err != nil {
  488. return err
  489. } else if err = os.MkdirAll(UserPath(u.Name), os.ModePerm); err != nil {
  490. return err
  491. }
  492. return sess.Commit()
  493. }
  494. func countUsers(e Engine) int64 {
  495. count, _ := e.Where("type=0").Count(new(User))
  496. return count
  497. }
  498. // CountUsers returns number of users.
  499. func CountUsers() int64 {
  500. return countUsers(x)
  501. }
  502. // Users returns number of users in given page.
  503. func Users(page, pageSize int) ([]*User, error) {
  504. users := make([]*User, 0, pageSize)
  505. return users, x.Limit(pageSize, (page-1)*pageSize).Where("type=0").Asc("id").Find(&users)
  506. }
  507. // parseUserFromCode returns user by username encoded in code.
  508. // It returns nil if code or username is invalid.
  509. func parseUserFromCode(code string) (user *User) {
  510. if len(code) <= tool.TIME_LIMIT_CODE_LENGTH {
  511. return nil
  512. }
  513. // Use tail hex username to query user
  514. hexStr := code[tool.TIME_LIMIT_CODE_LENGTH:]
  515. if b, err := hex.DecodeString(hexStr); err == nil {
  516. if user, err = GetUserByName(string(b)); user != nil {
  517. return user
  518. } else if !errors.IsUserNotExist(err) {
  519. log.Error("GetUserByName: %v", err)
  520. }
  521. }
  522. return nil
  523. }
  524. // verify active code when active account
  525. func VerifyUserActiveCode(code string) (user *User) {
  526. minutes := conf.Auth.ActivateCodeLives
  527. if user = parseUserFromCode(code); user != nil {
  528. // time limit code
  529. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  530. data := com.ToStr(user.ID) + user.Email + user.LowerName + user.Passwd + user.Rands
  531. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  532. return user
  533. }
  534. }
  535. return nil
  536. }
  537. // verify active code when active account
  538. func VerifyActiveEmailCode(code, email string) *EmailAddress {
  539. minutes := conf.Auth.ActivateCodeLives
  540. if user := parseUserFromCode(code); user != nil {
  541. // time limit code
  542. prefix := code[:tool.TIME_LIMIT_CODE_LENGTH]
  543. data := com.ToStr(user.ID) + email + user.LowerName + user.Passwd + user.Rands
  544. if tool.VerifyTimeLimitCode(data, minutes, prefix) {
  545. emailAddress := &EmailAddress{Email: email}
  546. if has, _ := x.Get(emailAddress); has {
  547. return emailAddress
  548. }
  549. }
  550. }
  551. return nil
  552. }
  553. // ChangeUserName changes all corresponding setting from old user name to new one.
  554. func ChangeUserName(u *User, newUserName string) (err error) {
  555. if err = IsUsableUsername(newUserName); err != nil {
  556. return err
  557. }
  558. isExist, err := IsUserExist(0, newUserName)
  559. if err != nil {
  560. return err
  561. } else if isExist {
  562. return ErrUserAlreadyExist{newUserName}
  563. }
  564. if err = ChangeUsernameInPullRequests(u.Name, newUserName); err != nil {
  565. return fmt.Errorf("ChangeUsernameInPullRequests: %v", err)
  566. }
  567. // Delete all local copies of repositories and wikis the user owns.
  568. if err = x.Where("owner_id=?", u.ID).Iterate(new(Repository), func(idx int, bean interface{}) error {
  569. repo := bean.(*Repository)
  570. deleteRepoLocalCopy(repo)
  571. // TODO: By the same reasoning, shouldn't we also sync access to the local wiki path?
  572. RemoveAllWithNotice("Delete repository wiki local copy", repo.LocalWikiPath())
  573. return nil
  574. }); err != nil {
  575. return fmt.Errorf("delete repository and 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 sess.Close()
  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 RewriteAuthorizedKeys()
  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(conf.Repository.Root, 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: 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{UserID: 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: userID}
  782. }
  783. return GetUserByID(userID)
  784. }
  785. // GetUserByName returns a user by given name.
  786. func GetUserByName(name string) (*User, error) {
  787. if len(name) == 0 {
  788. return nil, errors.UserNotExist{Name: 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{Name: 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 []*git.Commit) []*UserCommit {
  840. emails := make(map[string]*User)
  841. newCommits := make([]*UserCommit, len(oldCommits))
  842. for i := range oldCommits {
  843. var u *User
  844. if v, ok := emails[oldCommits[i].Author.Email]; !ok {
  845. u, _ = GetUserByEmail(oldCommits[i].Author.Email)
  846. emails[oldCommits[i].Author.Email] = u
  847. } else {
  848. u = v
  849. }
  850. newCommits[i] = &UserCommit{
  851. User: u,
  852. Commit: oldCommits[i],
  853. }
  854. }
  855. return newCommits
  856. }
  857. // GetUserByEmail returns the user object by given e-mail if exists.
  858. func GetUserByEmail(email string) (*User, error) {
  859. if len(email) == 0 {
  860. return nil, errors.UserNotExist{Name: "email"}
  861. }
  862. email = strings.ToLower(email)
  863. // First try to find the user by primary email
  864. user := &User{Email: email}
  865. has, err := x.Get(user)
  866. if err != nil {
  867. return nil, err
  868. }
  869. if has {
  870. return user, nil
  871. }
  872. // Otherwise, check in alternative list for activated email addresses
  873. emailAddress := &EmailAddress{Email: email, IsActivated: true}
  874. has, err = x.Get(emailAddress)
  875. if err != nil {
  876. return nil, err
  877. }
  878. if has {
  879. return GetUserByID(emailAddress.UID)
  880. }
  881. return nil, errors.UserNotExist{Name: email}
  882. }
  883. type SearchUserOptions struct {
  884. Keyword string
  885. Type UserType
  886. OrderBy string
  887. Page int
  888. PageSize int // Can be smaller than or equal to setting.UI.ExplorePagingNum
  889. }
  890. // SearchUserByName takes keyword and part of user name to search,
  891. // it returns results in given range and number of total results.
  892. func SearchUserByName(opts *SearchUserOptions) (users []*User, _ int64, _ error) {
  893. if len(opts.Keyword) == 0 {
  894. return users, 0, nil
  895. }
  896. opts.Keyword = strings.ToLower(opts.Keyword)
  897. if opts.PageSize <= 0 || opts.PageSize > conf.UI.ExplorePagingNum {
  898. opts.PageSize = conf.UI.ExplorePagingNum
  899. }
  900. if opts.Page <= 0 {
  901. opts.Page = 1
  902. }
  903. searchQuery := "%" + opts.Keyword + "%"
  904. users = make([]*User, 0, opts.PageSize)
  905. // Append conditions
  906. sess := x.Where("LOWER(lower_name) LIKE ?", searchQuery).
  907. Or("LOWER(full_name) LIKE ?", searchQuery).
  908. And("type = ?", opts.Type)
  909. var countSess xorm.Session
  910. countSess = *sess
  911. count, err := countSess.Count(new(User))
  912. if err != nil {
  913. return nil, 0, fmt.Errorf("Count: %v", err)
  914. }
  915. if len(opts.OrderBy) > 0 {
  916. sess.OrderBy(opts.OrderBy)
  917. }
  918. return users, count, sess.Limit(opts.PageSize, (opts.Page-1)*opts.PageSize).Find(&users)
  919. }
  920. // ___________ .__ .__
  921. // \_ _____/___ | | | | ______ _ __
  922. // | __)/ _ \| | | | / _ \ \/ \/ /
  923. // | \( <_> ) |_| |_( <_> ) /
  924. // \___ / \____/|____/____/\____/ \/\_/
  925. // \/
  926. // Follow represents relations of user and his/her followers.
  927. type Follow struct {
  928. ID int64
  929. UserID int64 `xorm:"UNIQUE(follow)"`
  930. FollowID int64 `xorm:"UNIQUE(follow)"`
  931. }
  932. func IsFollowing(userID, followID int64) bool {
  933. has, _ := x.Get(&Follow{UserID: userID, FollowID: followID})
  934. return has
  935. }
  936. // FollowUser marks someone be another's follower.
  937. func FollowUser(userID, followID int64) (err error) {
  938. if userID == followID || IsFollowing(userID, followID) {
  939. return nil
  940. }
  941. sess := x.NewSession()
  942. defer sess.Close()
  943. if err = sess.Begin(); err != nil {
  944. return err
  945. }
  946. if _, err = sess.Insert(&Follow{UserID: userID, FollowID: followID}); err != nil {
  947. return err
  948. }
  949. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?", followID); err != nil {
  950. return err
  951. }
  952. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following + 1 WHERE id = ?", userID); err != nil {
  953. return err
  954. }
  955. return sess.Commit()
  956. }
  957. // UnfollowUser unmarks someone be another's follower.
  958. func UnfollowUser(userID, followID int64) (err error) {
  959. if userID == followID || !IsFollowing(userID, followID) {
  960. return nil
  961. }
  962. sess := x.NewSession()
  963. defer sess.Close()
  964. if err = sess.Begin(); err != nil {
  965. return err
  966. }
  967. if _, err = sess.Delete(&Follow{UserID: userID, FollowID: followID}); err != nil {
  968. return err
  969. }
  970. if _, err = sess.Exec("UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?", followID); err != nil {
  971. return err
  972. }
  973. if _, err = sess.Exec("UPDATE `user` SET num_following = num_following - 1 WHERE id = ?", userID); err != nil {
  974. return err
  975. }
  976. return sess.Commit()
  977. }