user.go 32 KB

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