user.go 31 KB

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