user.go 32 KB

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