user.go 31 KB

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