user.go 31 KB

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