user.go 31 KB

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