user.go 31 KB

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