user.go 31 KB

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