user.go 31 KB

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