user.go 32 KB

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