user.go 31 KB

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