user.go 31 KB

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