user.go 31 KB

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