From 4a6c56d2fdca7f3f7cbc6d03a6809796c0b5a56e Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 20 Mar 2014 09:49:06 -0400 Subject: Bug fix --- models/repo.go | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'models/repo.go') diff --git a/models/repo.go b/models/repo.go index 4b6dedaf90..052341ff6e 100644 --- a/models/repo.go +++ b/models/repo.go @@ -411,6 +411,10 @@ func DeleteRepository(userId, repoId int64, userName string) (err error) { session.Rollback() return err } + if _, err = session.Delete(&Watch{RepoId: repoId}); err != nil { + session.Rollback() + return err + } if err = session.Commit(); err != nil { session.Rollback() return err -- cgit v1.2.3 From 3b387336bfc097090d5b03f5b01e136bca56f8fd Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 20 Mar 2014 11:41:24 -0400 Subject: Add Repository/user name filter --- README.md | 2 +- gogs.go | 2 +- models/repo.go | 31 +++++++++++++++++++++++++++++++ models/user.go | 5 +++++ routers/repo/repo.go | 3 +++ routers/repo/single.go | 5 +++++ routers/user/user.go | 8 +++++--- 7 files changed, 51 insertions(+), 5 deletions(-) (limited to 'models/repo.go') diff --git a/README.md b/README.md index 3a1023c6d9..4219e4ed03 100644 --- a/README.md +++ b/README.md @@ -5,7 +5,7 @@ Gogs(Go Git Service) is a GitHub-like clone in the Go Programming Language. Since we choose to use pure Go implementation of Git manipulation, Gogs certainly supports **ALL platforms** that Go supports, including Linux, Max OS X, and Windows with **ZERO** dependency. -##### Current version: 0.1.1 Alpha +##### Current version: 0.1.4 Alpha ## Purpose diff --git a/gogs.go b/gogs.go index d32e3908c9..a600c53d12 100644 --- a/gogs.go +++ b/gogs.go @@ -20,7 +20,7 @@ import ( // Test that go1.1 tag above is included in builds. main.go refers to this definition. const go11tag = true -const APP_VER = "0.1.2.0320.1" +const APP_VER = "0.1.3.0320.1" func init() { base.AppVer = APP_VER diff --git a/models/repo.go b/models/repo.go index 052341ff6e..bcbc586785 100644 --- a/models/repo.go +++ b/models/repo.go @@ -12,6 +12,7 @@ import ( "os" "path" "path/filepath" + "regexp" "strings" "sync" "time" @@ -82,6 +83,7 @@ var ( ErrRepoAlreadyExist = errors.New("Repository already exist") ErrRepoNotExist = errors.New("Repository does not exist") ErrRepoFileNotExist = errors.New("Target Repo file does not exist") + ErrRepoNameIllegal = errors.New("Repository name contains illegal characters") ) func init() { @@ -104,6 +106,15 @@ func init() { os.Exit(2) } } + + // Initialize illegal patterns. + for i := range illegalPatterns[1:] { + pattern := "" + for j := range illegalPatterns[i+1] { + pattern += "[" + string(illegalPatterns[i+1][j]-32) + string(illegalPatterns[i+1][j]) + "]" + } + illegalPatterns[i+1] = pattern + } } // IsRepositoryExist returns true if the repository with given name under user has already existed. @@ -120,8 +131,28 @@ func IsRepositoryExist(user *User, repoName string) (bool, error) { return s.IsDir(), nil } +var ( + // Define as all lower case!! + illegalPatterns = []string{"[.][Gg][Ii][Tt]", "user", "help", "stars", "issues", "pulls", "commits", "admin", "repo", "template"} +) + +// IsLegalName returns false if name contains illegal characters. +func IsLegalName(repoName string) bool { + for _, pattern := range illegalPatterns { + has, _ := regexp.MatchString(pattern, repoName) + if has { + return false + } + } + return true +} + // CreateRepository creates a repository for given user or orgnaziation. func CreateRepository(user *User, repoName, desc, repoLang, license string, private bool, initReadme bool) (*Repository, error) { + if !IsLegalName(repoName) { + return nil, ErrRepoNameIllegal + } + isExist, err := IsRepositoryExist(user, repoName) if err != nil { return nil, err diff --git a/models/user.go b/models/user.go index fd89af6b3f..990e1954a5 100644 --- a/models/user.go +++ b/models/user.go @@ -79,6 +79,7 @@ var ( ErrUserAlreadyExist = errors.New("User already exist") ErrUserNotExist = errors.New("User does not exist") ErrEmailAlreadyUsed = errors.New("E-mail already used") + ErrUserNameIllegal = errors.New("User name contains illegal characters") ) // IsUserExist checks if given user name exist, @@ -108,6 +109,10 @@ func GetUserSalt() string { // RegisterUser creates record of a new user. func RegisterUser(user *User) (*User, error) { + if !IsLegalName(user.Name) { + return nil, ErrUserNameIllegal + } + isExist, err := IsUserExist(user.Name) if err != nil { return nil, err diff --git a/routers/repo/repo.go b/routers/repo/repo.go index 556cc4343c..c83a6df522 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -31,6 +31,9 @@ func Create(ctx *middleware.Context, form auth.CreateRepoForm) { } else if err == models.ErrRepoAlreadyExist { ctx.RenderWithErr("Repository name has already been used", "repo/create", &form) return + } else if err == models.ErrRepoNameIllegal { + ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), "repo/create", &form) + return } ctx.Handle(200, "repo.Create", err) } diff --git a/routers/repo/single.go b/routers/repo/single.go index f1b15cceed..eab49be919 100644 --- a/routers/repo/single.go +++ b/routers/repo/single.go @@ -217,6 +217,11 @@ func Setting(ctx *middleware.Context, params martini.Params) { title = t } + if len(params["branchname"]) == 0 { + params["branchname"] = "master" + } + + ctx.Data["Branchname"] = params["branchname"] ctx.Data["Title"] = title + " - settings" ctx.HTML(200, "repo/setting") } diff --git a/routers/user/user.go b/routers/user/user.go index be2c4d3839..ea6922591e 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -139,11 +139,13 @@ func SignUp(ctx *middleware.Context, form auth.RegisterForm) { var err error if u, err = models.RegisterUser(u); err != nil { - switch err.Error() { - case models.ErrUserAlreadyExist.Error(): + switch err { + case models.ErrUserAlreadyExist: ctx.RenderWithErr("Username has been already taken", "user/signup", &form) - case models.ErrEmailAlreadyUsed.Error(): + case models.ErrEmailAlreadyUsed: ctx.RenderWithErr("E-mail address has been already used", "user/signup", &form) + case models.ErrUserNameIllegal: + ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), "user/signup", &form) default: ctx.Handle(200, "user.SignUp", err) } -- cgit v1.2.3 From 06631ab91f5d84b48d6f71ac8eaf4df740ba0282 Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 20 Mar 2014 16:04:56 -0400 Subject: Basic admin data table, models changes --- README.md | 2 +- gogs.go | 8 +- models/issue.go | 19 ++++ models/models.go | 56 ++++------- models/publickey.go | 10 +- models/repo.go | 216 +++++++++++++++++++++-------------------- models/user.go | 97 +++++++++--------- modules/base/conf.go | 21 ++-- routers/admin/admin.go | 15 +++ serve.go | 4 +- templates/admin/dashboard.tmpl | 2 +- templates/admin/repos.tmpl | 24 +++++ templates/admin/users.tmpl | 26 +++++ 13 files changed, 291 insertions(+), 209 deletions(-) create mode 100644 models/issue.go (limited to 'models/repo.go') diff --git a/README.md b/README.md index 4219e4ed03..8c971fdb85 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ There are some very good products in this category such as [gitlab](http://gitla - Please see [Wiki](https://github.com/gogits/gogs/wiki) for project design, develop specification, change log and road map. - See [Trello Broad](https://trello.com/b/uxAoeLUl/gogs-go-git-service) to follow the develop team. -- Try it before anything? Go down to **Installation -> Install from binary** section!. +- Try it before anything? Do it [online](http://try.gogits.org/Unknown/gogs) or go down to **Installation -> Install from binary** section! - Having troubles? Get help from [Troubleshooting](https://github.com/gogits/gogs/wiki/Troubleshooting). ## Features diff --git a/gogs.go b/gogs.go index a600c53d12..a9f7e6b5c4 100644 --- a/gogs.go +++ b/gogs.go @@ -15,12 +15,12 @@ import ( "github.com/gogits/gogs/modules/base" ) -// +build go1.1 +// +build go1.2 -// Test that go1.1 tag above is included in builds. main.go refers to this definition. -const go11tag = true +// Test that go1.2 tag above is included in builds. main.go refers to this definition. +const go12tag = true -const APP_VER = "0.1.3.0320.1" +const APP_VER = "0.1.4.0321" func init() { base.AppVer = APP_VER diff --git a/models/issue.go b/models/issue.go new file mode 100644 index 0000000000..c669d201f6 --- /dev/null +++ b/models/issue.go @@ -0,0 +1,19 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package models + +type Issue struct { + Id int64 + RepoId int64 `xorm:"index"` + PosterId int64 +} + +type PullRequest struct { + Id int64 +} + +type Comment struct { + Id int64 +} diff --git a/models/models.go b/models/models.go index 2e0bb759d4..214d1c767a 100644 --- a/models/models.go +++ b/models/models.go @@ -15,30 +15,7 @@ import ( "github.com/gogits/gogs/modules/base" ) -var ( - orm *xorm.Engine - RepoRootPath string -) - -type Members struct { - Id int64 - OrgId int64 `xorm:"unique(s) index"` - UserId int64 `xorm:"unique(s)"` -} - -type Issue struct { - Id int64 - RepoId int64 `xorm:"index"` - PosterId int64 -} - -type PullRequest struct { - Id int64 -} - -type Comment struct { - Id int64 -} +var orm *xorm.Engine func setEngine() { dbType := base.Cfg.MustValue("database", "DB_TYPE") @@ -65,8 +42,8 @@ func setEngine() { os.Exit(2) } - // TODO: for serv command, MUST remove the output to os.stdout, so - // use log file to instead print to stdout + // WARNNING: for serv command, MUST remove the output to os.stdout, + // so use log file to instead print to stdout. //x.ShowDebug = true //orm.ShowErr = true @@ -77,20 +54,29 @@ func setEngine() { } orm.Logger = f orm.ShowSQL = true - - // Determine and create root git reposiroty path. - RepoRootPath = base.Cfg.MustValue("repository", "ROOT") - if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { - fmt.Printf("models.init(fail to create RepoRootPath(%s)): %v\n", RepoRootPath, err) - os.Exit(2) - } } func init() { setEngine() - if err := orm.Sync(new(User), new(PublicKey), new(Repository), new(Access), - new(Action), new(Watch)); err != nil { + if err := orm.Sync(new(User), new(PublicKey), new(Repository), new(Watch), + new(Action), new(Access)); err != nil { fmt.Printf("sync database struct error: %v\n", err) os.Exit(2) } } + +type Statistic struct { + Counter struct { + User, PublicKey, Repo, Watch, Action, Access int64 + } +} + +func GetStatistic() (stats Statistic) { + stats.Counter.User, _ = orm.Count(new(User)) + stats.Counter.PublicKey, _ = orm.Count(new(PublicKey)) + stats.Counter.Repo, _ = orm.Count(new(Repository)) + stats.Counter.Watch, _ = orm.Count(new(Watch)) + stats.Counter.Action, _ = orm.Count(new(Action)) + stats.Counter.Access, _ = orm.Count(new(Access)) + return stats +} diff --git a/models/publickey.go b/models/publickey.go index 092436d55f..c69bca681d 100644 --- a/models/publickey.go +++ b/models/publickey.go @@ -27,8 +27,12 @@ const ( ) var ( - sshOpLocker = sync.Mutex{} + ErrKeyAlreadyExist = errors.New("Public key already exist") +) +var sshOpLocker = sync.Mutex{} + +var ( sshPath string appPath string ) @@ -79,10 +83,6 @@ type PublicKey struct { Updated time.Time `xorm:"updated"` } -var ( - ErrKeyAlreadyExist = errors.New("Public key already exist") -) - // GenAuthorizedKey returns formatted public key string. func GenAuthorizedKey(keyId int64, key string) string { return fmt.Sprintf(TPL_PUBLICK_KEY+"\n", appPath, keyId, key) diff --git a/models/repo.go b/models/repo.go index bcbc586785..f7173d76d0 100644 --- a/models/repo.go +++ b/models/repo.go @@ -27,63 +27,18 @@ import ( "github.com/gogits/gogs/modules/log" ) -// Repository represents a git repository. -type Repository struct { - Id int64 - OwnerId int64 `xorm:"unique(s)"` - ForkId int64 - LowerName string `xorm:"unique(s) index not null"` - Name string `xorm:"index not null"` - Description string - Website string - Private bool - NumWatchs int - NumStars int - NumForks int - Created time.Time `xorm:"created"` - Updated time.Time `xorm:"updated"` -} - -// Watch is connection request for receiving repository notifycation. -type Watch struct { - Id int64 - RepoId int64 `xorm:"UNIQUE(watch)"` - UserId int64 `xorm:"UNIQUE(watch)"` -} - -// Watch or unwatch repository. -func WatchRepo(userId, repoId int64, watch bool) (err error) { - if watch { - _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}) - } else { - _, err = orm.Delete(&Watch{0, repoId, userId}) - } - return err -} - -// GetWatches returns all watches of given repository. -func GetWatches(repoId int64) ([]Watch, error) { - watches := make([]Watch, 0, 10) - err := orm.Find(&watches, &Watch{RepoId: repoId}) - return watches, err -} - -// IsWatching checks if user has watched given repository. -func IsWatching(userId, repoId int64) bool { - has, _ := orm.Get(&Watch{0, repoId, userId}) - return has -} - var ( - gitInitLocker = sync.Mutex{} - LanguageIgns, Licenses []string + ErrRepoAlreadyExist = errors.New("Repository already exist") + ErrRepoNotExist = errors.New("Repository does not exist") + ErrRepoFileNotExist = errors.New("Target Repo file does not exist") + ErrRepoNameIllegal = errors.New("Repository name contains illegal characters") + ErrRepoFileNotLoaded = fmt.Errorf("repo file not loaded") ) +var gitInitLocker = sync.Mutex{} + var ( - ErrRepoAlreadyExist = errors.New("Repository already exist") - ErrRepoNotExist = errors.New("Repository does not exist") - ErrRepoFileNotExist = errors.New("Target Repo file does not exist") - ErrRepoNameIllegal = errors.New("Repository name contains illegal characters") + LanguageIgns, Licenses []string ) func init() { @@ -117,6 +72,23 @@ func init() { } } +// Repository represents a git repository. +type Repository struct { + Id int64 + OwnerId int64 `xorm:"unique(s)"` + ForkId int64 + LowerName string `xorm:"unique(s) index not null"` + Name string `xorm:"index not null"` + Description string + Website string + Private bool + NumWatches int + NumStars int + NumForks int + Created time.Time `xorm:"created"` + Updated time.Time `xorm:"updated"` +} + // IsRepositoryExist returns true if the repository with given name under user has already existed. func IsRepositoryExist(user *User, repoName string) (bool, error) { repo := Repository{OwnerId: user.Id} @@ -351,6 +323,60 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep return nil } +// GetRepos returns given number of repository objects with offset. +func GetRepos(num, offset int) ([]Repository, error) { + repos := make([]Repository, 0, num) + err := orm.Limit(num, offset).Asc("id").Find(&repos) + return repos, err +} + +func RepoPath(userName, repoName string) string { + return filepath.Join(UserPath(userName), repoName+".git") +} + +// DeleteRepository deletes a repository for a user or orgnaztion. +func DeleteRepository(userId, repoId int64, userName string) (err error) { + repo := &Repository{Id: repoId, OwnerId: userId} + has, err := orm.Get(repo) + if err != nil { + return err + } else if !has { + return ErrRepoNotExist + } + + session := orm.NewSession() + if err = session.Begin(); err != nil { + return err + } + if _, err = session.Delete(&Repository{Id: repoId}); err != nil { + session.Rollback() + return err + } + if _, err := session.Delete(&Access{UserName: userName, RepoName: repo.Name}); err != nil { + session.Rollback() + return err + } + rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?" + if _, err = session.Exec(rawSql, userId); err != nil { + session.Rollback() + return err + } + if _, err = session.Delete(&Watch{RepoId: repoId}); err != nil { + session.Rollback() + return err + } + if err = session.Commit(); err != nil { + session.Rollback() + return err + } + if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil { + // TODO: log and delete manully + log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err) + return err + } + return nil +} + // GetRepositoryByName returns the repository by given name under user if exists. func GetRepositoryByName(user *User, repoName string) (*Repository, error) { repo := &Repository{ @@ -388,6 +414,36 @@ func GetRepositoryCount(user *User) (int64, error) { return orm.Count(&Repository{OwnerId: user.Id}) } +// Watch is connection request for receiving repository notifycation. +type Watch struct { + Id int64 + RepoId int64 `xorm:"UNIQUE(watch)"` + UserId int64 `xorm:"UNIQUE(watch)"` +} + +// Watch or unwatch repository. +func WatchRepo(userId, repoId int64, watch bool) (err error) { + if watch { + _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}) + } else { + _, err = orm.Delete(&Watch{0, repoId, userId}) + } + return err +} + +// GetWatches returns all watches of given repository. +func GetWatches(repoId int64) ([]Watch, error) { + watches := make([]Watch, 0, 10) + err := orm.Find(&watches, &Watch{RepoId: repoId}) + return watches, err +} + +// IsWatching checks if user has watched given repository. +func IsWatching(userId, repoId int64) bool { + has, _ := orm.Get(&Watch{0, repoId, userId}) + return has +} + func StarReposiory(user *User, repoName string) error { return nil } @@ -408,60 +464,6 @@ func ForkRepository(reposName string, userId int64) { } -func RepoPath(userName, repoName string) string { - return filepath.Join(UserPath(userName), repoName+".git") -} - -// DeleteRepository deletes a repository for a user or orgnaztion. -func DeleteRepository(userId, repoId int64, userName string) (err error) { - repo := &Repository{Id: repoId, OwnerId: userId} - has, err := orm.Get(repo) - if err != nil { - return err - } else if !has { - return ErrRepoNotExist - } - - session := orm.NewSession() - if err = session.Begin(); err != nil { - return err - } - if _, err = session.Delete(&Repository{Id: repoId}); err != nil { - session.Rollback() - return err - } - if _, err := session.Delete(&Access{UserName: userName, RepoName: repo.Name}); err != nil { - session.Rollback() - return err - } - rawSql := "UPDATE user SET num_repos = num_repos - 1 WHERE id = ?" - if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" { - rawSql = "UPDATE \"user\" SET num_repos = num_repos - 1 WHERE id = ?" - } - if _, err = session.Exec(rawSql, userId); err != nil { - session.Rollback() - return err - } - if _, err = session.Delete(&Watch{RepoId: repoId}); err != nil { - session.Rollback() - return err - } - if err = session.Commit(); err != nil { - session.Rollback() - return err - } - if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil { - // TODO: log and delete manully - log.Error("delete repo %s/%s failed: %v", userName, repo.Name, err) - return err - } - return nil -} - -var ( - ErrRepoFileNotLoaded = fmt.Errorf("repo file not loaded") -) - // RepoFile represents a file object in git repository. type RepoFile struct { *git.TreeEntry diff --git a/models/user.go b/models/user.go index 990e1954a5..3c11091285 100644 --- a/models/user.go +++ b/models/user.go @@ -33,6 +33,14 @@ const ( LT_LDAP ) +var ( + ErrUserOwnRepos = errors.New("User still have ownership of repositories") + ErrUserAlreadyExist = errors.New("User already exist") + ErrUserNotExist = errors.New("User does not exist") + ErrEmailAlreadyUsed = errors.New("E-mail already used") + ErrUserNameIllegal = errors.New("User name contains illegal characters") +) + // User represents the object of individual and member of organization. type User struct { Id int64 @@ -67,20 +75,28 @@ func (user *User) AvatarLink() string { return "http://1.gravatar.com/avatar/" + user.Avatar } -type Follow struct { - Id int64 - UserId int64 `xorm:"unique(s)"` - FollowId int64 `xorm:"unique(s)"` - Created time.Time `xorm:"created"` +// NewGitSig generates and returns the signature of given user. +func (user *User) NewGitSig() *git.Signature { + return &git.Signature{ + Name: user.Name, + Email: user.Email, + When: time.Now(), + } } -var ( - ErrUserOwnRepos = errors.New("User still have ownership of repositories") - ErrUserAlreadyExist = errors.New("User already exist") - ErrUserNotExist = errors.New("User does not exist") - ErrEmailAlreadyUsed = errors.New("E-mail already used") - ErrUserNameIllegal = errors.New("User name contains illegal characters") -) +// EncodePasswd encodes password to safe format. +func (user *User) EncodePasswd() error { + newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(base.SecretKey), 16384, 8, 1, 64) + user.Passwd = fmt.Sprintf("%x", newPasswd) + return err +} + +// Member represents user is member of organization. +type Member struct { + Id int64 + OrgId int64 `xorm:"unique(member) index"` + UserId int64 `xorm:"unique(member)"` +} // IsUserExist checks if given user name exist, // the user name should be noncased unique. @@ -93,15 +109,6 @@ func IsEmailUsed(email string) (bool, error) { return orm.Get(&User{Email: email}) } -// NewGitSig generates and returns the signature of given user. -func (user *User) NewGitSig() *git.Signature { - return &git.Signature{ - Name: user.Name, - Email: user.Email, - When: time.Now(), - } -} - // return a user salt token func GetUserSalt() string { return base.GetRandomString(10) @@ -151,6 +158,13 @@ func RegisterUser(user *User) (*User, error) { return user, err } +// GetUsers returns given number of user objects with offset. +func GetUsers(num, offset int) ([]User, error) { + users := make([]User, 0, num) + err := orm.Limit(num, offset).Asc("id").Find(&users) + return users, err +} + // get user by erify code func getVerifyUser(code string) (user *User) { if len(code) <= base.TimeLimitCodeLength { @@ -229,24 +243,14 @@ func DeleteUser(user *User) error { return err } -// EncodePasswd encodes password to safe format. -func (user *User) EncodePasswd() error { - newPasswd, err := scrypt.Key([]byte(user.Passwd), []byte(base.SecretKey), 16384, 8, 1, 64) - user.Passwd = fmt.Sprintf("%x", newPasswd) - return err -} - // UserPath returns the path absolute path of user repositories. func UserPath(userName string) string { - return filepath.Join(RepoRootPath, strings.ToLower(userName)) + return filepath.Join(base.RepoRootPath, strings.ToLower(userName)) } func GetUserByKeyId(keyId int64) (*User, error) { user := new(User) - rawSql := "SELECT a.* FROM user AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?" - if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" { - rawSql = "SELECT a.* FROM \"user\" AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?" - } + rawSql := "SELECT a.* FROM `user` AS a, public_key AS b WHERE a.id = b.owner_id AND b.id=?" has, err := orm.Sql(rawSql, keyId).Get(user) if err != nil { return nil, err @@ -303,6 +307,13 @@ func LoginUserPlain(name, passwd string) (*User, error) { return &user, err } +// Follow is connection request for receiving user notifycation. +type Follow struct { + Id int64 + UserId int64 `xorm:"unique(follow)"` + FollowId int64 `xorm:"unique(follow)"` +} + // FollowUser marks someone be another's follower. func FollowUser(userId int64, followId int64) (err error) { session := orm.NewSession() @@ -314,19 +325,13 @@ func FollowUser(userId int64, followId int64) (err error) { return err } - rawSql := "UPDATE user SET num_followers = num_followers + 1 WHERE id = ?" - if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" { - rawSql = "UPDATE \"user\" SET num_followers = num_followers + 1 WHERE id = ?" - } + rawSql := "UPDATE `user` SET num_followers = num_followers + 1 WHERE id = ?" if _, err = session.Exec(rawSql, followId); err != nil { session.Rollback() return err } - rawSql = "UPDATE user SET num_followings = num_followings + 1 WHERE id = ?" - if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" { - rawSql = "UPDATE \"user\" SET num_followings = num_followings + 1 WHERE id = ?" - } + rawSql = "UPDATE `user` SET num_followings = num_followings + 1 WHERE id = ?" if _, err = session.Exec(rawSql, userId); err != nil { session.Rollback() return err @@ -345,19 +350,13 @@ func UnFollowUser(userId int64, unFollowId int64) (err error) { return err } - rawSql := "UPDATE user SET num_followers = num_followers - 1 WHERE id = ?" - if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" { - rawSql = "UPDATE \"user\" SET num_followers = num_followers - 1 WHERE id = ?" - } + rawSql := "UPDATE `user` SET num_followers = num_followers - 1 WHERE id = ?" if _, err = session.Exec(rawSql, unFollowId); err != nil { session.Rollback() return err } - rawSql = "UPDATE user SET num_followings = num_followings - 1 WHERE id = ?" - if base.Cfg.MustValue("database", "DB_TYPE") == "postgres" { - rawSql = "UPDATE \"user\" SET num_followings = num_followings - 1 WHERE id = ?" - } + rawSql = "UPDATE `user` SET num_followings = num_followings - 1 WHERE id = ?" if _, err = session.Exec(rawSql, userId); err != nil { session.Rollback() return err diff --git a/modules/base/conf.go b/modules/base/conf.go index fdbf3ad385..81f32bd591 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -26,12 +26,14 @@ type Mailer struct { } var ( - AppVer string - AppName string - AppLogo string - AppUrl string - Domain string - SecretKey string + AppVer string + AppName string + AppLogo string + AppUrl string + Domain string + SecretKey string + RepoRootPath string + Cfg *goconfig.ConfigFile MailService *Mailer ) @@ -173,6 +175,13 @@ func init() { AppUrl = Cfg.MustValue("server", "ROOT_URL") Domain = Cfg.MustValue("server", "DOMAIN") SecretKey = Cfg.MustValue("security", "SECRET_KEY") + + // Determine and create root git reposiroty path. + RepoRootPath = Cfg.MustValue("repository", "ROOT") + if err = os.MkdirAll(RepoRootPath, os.ModePerm); err != nil { + fmt.Printf("models.init(fail to create RepoRootPath(%s)): %v\n", RepoRootPath, err) + os.Exit(2) + } } func NewServices() { diff --git a/routers/admin/admin.go b/routers/admin/admin.go index c7523b7f59..a37f1207c9 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -5,20 +5,35 @@ package admin import ( + "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/middleware" ) func Dashboard(ctx *middleware.Context) { ctx.Data["Title"] = "Admin Dashboard" + ctx.Data["Stats"] = models.GetStatistic() ctx.HTML(200, "admin/dashboard") } func Users(ctx *middleware.Context) { ctx.Data["Title"] = "User Management" + + var err error + ctx.Data["Users"], err = models.GetUsers(100, 0) + if err != nil { + ctx.Handle(200, "admin.Users", err) + return + } ctx.HTML(200, "admin/users") } func Repositories(ctx *middleware.Context) { ctx.Data["Title"] = "Repository Management" + var err error + ctx.Data["Repos"], err = models.GetRepos(100, 0) + if err != nil { + ctx.Handle(200, "admin.Repositories", err) + return + } ctx.HTML(200, "admin/repos") } diff --git a/serve.go b/serve.go index ddc670235e..2a17a33490 100644 --- a/serve.go +++ b/serve.go @@ -12,7 +12,9 @@ import ( "strings" "github.com/codegangsta/cli" + "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/base" ) var ( @@ -144,7 +146,7 @@ func runServ(*cli.Context) { } gitcmd := exec.Command(verb, rRepo) - gitcmd.Dir = models.RepoRootPath + gitcmd.Dir = base.RepoRootPath gitcmd.Stdout = os.Stdout gitcmd.Stdin = os.Stdin gitcmd.Stderr = os.Stderr diff --git a/templates/admin/dashboard.tmpl b/templates/admin/dashboard.tmpl index 84456c85b8..6a914b65f7 100644 --- a/templates/admin/dashboard.tmpl +++ b/templates/admin/dashboard.tmpl @@ -16,7 +16,7 @@
- Gogs database has 4 users, 3 repositories, 4 SSH keys. + Gogs database has {{.Stats.Counter.User}} users, {{.Stats.Counter.PublicKey}} SSH keys, {{.Stats.Counter.Repo}} repositories, {{.Stats.Counter.Watch}} watches, {{.Stats.Counter.Action}} actions, and {{.Stats.Counter.Access}} accesses.
diff --git a/templates/admin/repos.tmpl b/templates/admin/repos.tmpl index ec7f47e090..4522c66792 100644 --- a/templates/admin/repos.tmpl +++ b/templates/admin/repos.tmpl @@ -16,6 +16,30 @@
+ + + + + + + + + + + + + {{range .Repos}} + + + + + + + + + {{end}} + +
IdNamePrivateWatchesForksCreated
{{.Id}}{{.Name}}{{.NumWatches}}{{.NumForks}}{{DateFormat .Created "M d, Y"}}
diff --git a/templates/admin/users.tmpl b/templates/admin/users.tmpl index 8acf256d05..c087f268f2 100644 --- a/templates/admin/users.tmpl +++ b/templates/admin/users.tmpl @@ -16,6 +16,32 @@
+ + + + + + + + + + + + + + {{range .Users}} + + + + + + + + + + {{end}} + +
IdNameE-mailActivedAdminReposJoin
{{.Id}}{{.Name}}{{.Email}}{{.NumRepos}}{{DateFormat .Created "M d, Y"}}
-- cgit v1.2.3 From 53a17bbd240e0dd3755b7a666792d69e358f3e00 Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 20 Mar 2014 16:14:50 -0400 Subject: Bug fix --- models/repo.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) (limited to 'models/repo.go') diff --git a/models/repo.go b/models/repo.go index f7173d76d0..f5ceaf7631 100644 --- a/models/repo.go +++ b/models/repo.go @@ -424,9 +424,18 @@ type Watch struct { // Watch or unwatch repository. func WatchRepo(userId, repoId int64, watch bool) (err error) { if watch { - _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}) + if _, err = orm.Insert(&Watch{RepoId: repoId, UserId: userId}); err != nil { + return err + } + + rawSql := "UPDATE `repository` SET num_watches = num_watches + 1 WHERE id = ?" + _, err = orm.Exec(rawSql, repoId) } else { - _, err = orm.Delete(&Watch{0, repoId, userId}) + if _, err = orm.Delete(&Watch{0, repoId, userId}); err != nil { + return err + } + rawSql := "UPDATE `repository` SET num_watches = num_watches - 1 WHERE id = ?" + _, err = orm.Exec(rawSql, repoId) } return err } -- cgit v1.2.3 From 369ddf76a8ae6916ab72f1fa26c81b44c456c6ea Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 21 Mar 2014 01:09:22 -0400 Subject: Batch fix --- README.md | 2 +- conf/app.ini | 8 +++++++- models/action.go | 4 ++++ models/models.go | 5 +++++ models/repo.go | 28 +++++++++++++++++++++++++--- modules/base/conf.go | 8 +++++--- modules/base/template.go | 11 ++++++++++- routers/user/user.go | 6 ++++++ templates/admin/repos.tmpl | 4 +++- templates/admin/users.tmpl | 2 +- templates/base/navbar.tmpl | 3 ++- templates/repo/single.tmpl | 2 +- templates/user/signin.tmpl | 2 +- templates/user/signup.tmpl | 4 ++++ 14 files changed, 75 insertions(+), 14 deletions(-) (limited to 'models/repo.go') diff --git a/README.md b/README.md index 8c971fdb85..3668ae8998 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ There are some very good products in this category such as [gitlab](http://gitla - Repository viewer. - Gravatar support. - Mail service(register). -- Supports MySQL and PostgreSQL. +- Supports MySQL, PostgreSQL and SQLite3(binary release only). ## Installation diff --git a/conf/app.ini b/conf/app.ini index 658f7c0151..d38cd1f05e 100644 --- a/conf/app.ini +++ b/conf/app.ini @@ -18,7 +18,7 @@ HTTP_ADDR = HTTP_PORT = 3000 [database] -; Either "mysql" or "postgres", it's your choice +; Either "mysql", "postgres" or "sqlite3"(binary release only), it's your choice DB_TYPE = mysql HOST = NAME = gogs @@ -26,6 +26,10 @@ USER = root PASSWD = ; For "postgres" only, either "disable", "require" or "verify-full" SSL_MODE = disable +; For "sqlite3" only +PATH = data/gogs.db + +[admin] [security] ; !!CHANGE THIS TO KEEP YOUR USER DATA SAFE!! @@ -36,6 +40,8 @@ ACTIVE_CODE_LIVE_MINUTES = 180 RESET_PASSWD_CODE_LIVE_MINUTES = 180 ; User need to confirm e-mail for registration REGISTER_EMAIL_CONFIRM = false +; Does not allow register and admin create account only +DISENABLE_REGISTERATION = false [mailer] ENABLED = false diff --git a/models/action.go b/models/action.go index b3be093533..107d4b1057 100644 --- a/models/action.go +++ b/models/action.go @@ -64,6 +64,10 @@ func CommitRepoAction(userId int64, userName string, watches = append(watches, Watch{UserId: userId}) for i := range watches { + if userId == watches[i].UserId && i > 0 { + continue // Do not add twice in case author watches his/her repository. + } + _, err = orm.InsertOne(&Action{ UserId: watches[i].UserId, ActUserId: userId, diff --git a/models/models.go b/models/models.go index 214d1c767a..8df230975f 100644 --- a/models/models.go +++ b/models/models.go @@ -7,6 +7,7 @@ package models import ( "fmt" "os" + "path" _ "github.com/go-sql-driver/mysql" _ "github.com/lib/pq" @@ -23,6 +24,7 @@ func setEngine() { dbName := base.Cfg.MustValue("database", "NAME") dbUser := base.Cfg.MustValue("database", "USER") dbPwd := base.Cfg.MustValue("database", "PASSWD") + dbPath := base.Cfg.MustValue("database", "PATH", "data/gogs.db") sslMode := base.Cfg.MustValue("database", "SSL_MODE") var err error @@ -33,6 +35,9 @@ func setEngine() { case "postgres": orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s", dbUser, dbPwd, dbName, sslMode)) + case "sqlite3": + os.MkdirAll(path.Dir(dbPath), os.ModePerm) + orm, err = xorm.NewEngine("sqlite3", dbPath) default: fmt.Printf("Unknown database type: %s\n", dbType) os.Exit(2) diff --git a/models/repo.go b/models/repo.go index f5ceaf7631..93f68ceddf 100644 --- a/models/repo.go +++ b/models/repo.go @@ -323,11 +323,33 @@ func initRepository(f string, user *User, repo *Repository, initReadme bool, rep return nil } +// UserRepo reporesents a repository with user name. +type UserRepo struct { + *Repository + UserName string +} + // GetRepos returns given number of repository objects with offset. -func GetRepos(num, offset int) ([]Repository, error) { +func GetRepos(num, offset int) ([]UserRepo, error) { repos := make([]Repository, 0, num) - err := orm.Limit(num, offset).Asc("id").Find(&repos) - return repos, err + if err := orm.Limit(num, offset).Asc("id").Find(&repos); err != nil { + return nil, err + } + + urepos := make([]UserRepo, len(repos)) + for i := range repos { + urepos[i].Repository = &repos[i] + u := new(User) + has, err := orm.Id(urepos[i].Repository.OwnerId).Get(u) + if err != nil { + return nil, err + } else if !has { + return nil, ErrUserNotExist + } + urepos[i].UserName = u.Name + } + + return urepos, nil } func RepoPath(userName, repoName string) string { diff --git a/modules/base/conf.go b/modules/base/conf.go index 81f32bd591..41b66b69f8 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -39,9 +39,10 @@ var ( ) var Service struct { - RegisterEmailConfirm bool - ActiveCodeLives int - ResetPwdCodeLives int + RegisterEmailConfirm bool + DisenableRegisteration bool + ActiveCodeLives int + ResetPwdCodeLives int } func exeDir() (string, error) { @@ -68,6 +69,7 @@ var logLevels = map[string]string{ func newService() { Service.ActiveCodeLives = Cfg.MustInt("service", "ACTIVE_CODE_LIVE_MINUTES", 180) Service.ResetPwdCodeLives = Cfg.MustInt("service", "RESET_PASSWD_CODE_LIVE_MINUTES", 180) + Service.DisenableRegisteration = Cfg.MustBool("service", "DISENABLE_REGISTERATION", false) } func newLogService() { diff --git a/modules/base/template.go b/modules/base/template.go index e596d1dada..8d95dbeab7 100644 --- a/modules/base/template.go +++ b/modules/base/template.go @@ -33,6 +33,10 @@ func List(l *list.List) chan interface{} { return c } +var mailDomains = map[string]string{ + "gmail.com": "gmail.com", +} + var TemplateFuncs template.FuncMap = map[string]interface{}{ "AppName": func() string { return AppName @@ -56,7 +60,12 @@ var TemplateFuncs template.FuncMap = map[string]interface{}{ "DateFormat": DateFormat, "List": List, "Mail2Domain": func(mail string) string { - return "mail." + strings.Split(mail, "@")[1] + suffix := strings.SplitN(mail, "@", 2)[1] + domain, ok := mailDomains[suffix] + if !ok { + return "mail." + suffix + } + return domain }, "SubStr": func(str string, start, length int) string { return str[start : start+length] diff --git a/routers/user/user.go b/routers/user/user.go index ea6922591e..40b594ab80 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -112,6 +112,12 @@ func SignUp(ctx *middleware.Context, form auth.RegisterForm) { ctx.Data["Title"] = "Sign Up" ctx.Data["PageIsSignUp"] = true + if base.Service.DisenableRegisteration { + ctx.Data["DisenableRegisteration"] = true + ctx.HTML(200, "user/signup") + return + } + if ctx.Req.Method == "GET" { ctx.HTML(200, "user/signup") return diff --git a/templates/admin/repos.tmpl b/templates/admin/repos.tmpl index 4522c66792..f4834c9060 100644 --- a/templates/admin/repos.tmpl +++ b/templates/admin/repos.tmpl @@ -20,6 +20,7 @@ Id + Owner Name Private Watches @@ -31,7 +32,8 @@ {{range .Repos}} {{.Id}} - {{.Name}} + {{.UserName}} + {{.Name}} {{.NumWatches}} {{.NumForks}} diff --git a/templates/admin/users.tmpl b/templates/admin/users.tmpl index c087f268f2..b690e1771e 100644 --- a/templates/admin/users.tmpl +++ b/templates/admin/users.tmpl @@ -32,7 +32,7 @@ {{range .Users}} {{.Id}} - {{.Name}} + {{.Name}} {{.Email}} diff --git a/templates/base/navbar.tmpl b/templates/base/navbar.tmpl index 9c064d07e7..d775191a5a 100644 --- a/templates/base/navbar.tmpl +++ b/templates/base/navbar.tmpl @@ -11,7 +11,8 @@ {{if .IsAdmin}}{{end}} - {{else}}Sign in{{end}} + {{else}}Sign In + Sign Up{{end}} diff --git a/templates/repo/single.tmpl b/templates/repo/single.tmpl index 8a7b5e479b..a1c3cfbb26 100644 --- a/templates/repo/single.tmpl +++ b/templates/repo/single.tmpl @@ -15,7 +15,7 @@ diff --git a/templates/user/signin.tmpl b/templates/user/signin.tmpl index e60cedec88..a49bf11405 100644 --- a/templates/user/signin.tmpl +++ b/templates/user/signin.tmpl @@ -32,7 +32,7 @@ diff --git a/templates/user/signup.tmpl b/templates/user/signup.tmpl index 187364de8f..069d34a5b2 100644 --- a/templates/user/signup.tmpl +++ b/templates/user/signup.tmpl @@ -2,6 +2,9 @@ {{template "base/navbar" .}}
+ {{if .DisenableRegisteration}} + Sorry, registeration has been disenabled, you can only get account from administrator. + {{else}}

Sign Up

{{.ErrorMsg}}
+ {{end}} {{template "base/footer" .}} \ No newline at end of file -- cgit v1.2.3 From f6596f11c4aacd3c7c30098f7ffe79e936d21583 Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 21 Mar 2014 01:48:10 -0400 Subject: All configuration reload-able --- README.md | 1 + models/models.go | 39 ++++++++++++++++++++++++--------------- models/models_test.go | 3 +++ models/repo.go | 4 +++- modules/base/conf.go | 2 +- modules/mailer/mailer.go | 2 +- routers/admin/admin.go | 10 ++++++++++ templates/admin/config.tmpl | 17 +++++++++++++++++ templates/admin/dashboard.tmpl | 9 +-------- templates/admin/nav.tmpl | 8 ++++++++ templates/admin/repos.tmpl | 9 +-------- templates/admin/users.tmpl | 9 +-------- web.go | 20 +++++++++++++++++--- 13 files changed, 88 insertions(+), 45 deletions(-) create mode 100644 templates/admin/config.tmpl create mode 100644 templates/admin/nav.tmpl (limited to 'models/repo.go') diff --git a/README.md b/README.md index 3668ae8998..e78ce8fe99 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ There are some very good products in this category such as [gitlab](http://gitla - Repository viewer. - Gravatar support. - Mail service(register). +- Administration panel. - Supports MySQL, PostgreSQL and SQLite3(binary release only). ## Installation diff --git a/models/models.go b/models/models.go index 8df230975f..bb0015d3de 100644 --- a/models/models.go +++ b/models/models.go @@ -16,30 +16,39 @@ import ( "github.com/gogits/gogs/modules/base" ) -var orm *xorm.Engine +var ( + orm *xorm.Engine + + dbCfg struct { + Type, Host, Name, User, Pwd, Path, SslMode string + } +) + +func LoadModelsConfig() { + dbCfg.Type = base.Cfg.MustValue("database", "DB_TYPE") + dbCfg.Host = base.Cfg.MustValue("database", "HOST") + dbCfg.Name = base.Cfg.MustValue("database", "NAME") + dbCfg.User = base.Cfg.MustValue("database", "USER") + dbCfg.Pwd = base.Cfg.MustValue("database", "PASSWD") + dbCfg.Path = base.Cfg.MustValue("database", "PATH", "data/gogs.db") + dbCfg.SslMode = base.Cfg.MustValue("database", "SSL_MODE") +} func setEngine() { - dbType := base.Cfg.MustValue("database", "DB_TYPE") - dbHost := base.Cfg.MustValue("database", "HOST") - dbName := base.Cfg.MustValue("database", "NAME") - dbUser := base.Cfg.MustValue("database", "USER") - dbPwd := base.Cfg.MustValue("database", "PASSWD") - dbPath := base.Cfg.MustValue("database", "PATH", "data/gogs.db") - sslMode := base.Cfg.MustValue("database", "SSL_MODE") var err error - switch dbType { + switch dbCfg.Type { case "mysql": orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@%s/%s?charset=utf8", - dbUser, dbPwd, dbHost, dbName)) + dbCfg.User, dbCfg.Pwd, dbCfg.Host, dbCfg.Name)) case "postgres": orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s", - dbUser, dbPwd, dbName, sslMode)) + dbCfg.User, dbCfg.Pwd, dbCfg.Name, dbCfg.SslMode)) case "sqlite3": - os.MkdirAll(path.Dir(dbPath), os.ModePerm) - orm, err = xorm.NewEngine("sqlite3", dbPath) + os.MkdirAll(path.Dir(dbCfg.Path), os.ModePerm) + orm, err = xorm.NewEngine("sqlite3", dbCfg.Path) default: - fmt.Printf("Unknown database type: %s\n", dbType) + fmt.Printf("Unknown database type: %s\n", dbCfg.Type) os.Exit(2) } if err != nil { @@ -61,7 +70,7 @@ func setEngine() { orm.ShowSQL = true } -func init() { +func NewEngine() { setEngine() if err := orm.Sync(new(User), new(PublicKey), new(Repository), new(Watch), new(Action), new(Access)); err != nil { diff --git a/models/models_test.go b/models/models_test.go index c44ef476c6..d0f734d678 100644 --- a/models/models_test.go +++ b/models/models_test.go @@ -13,6 +13,9 @@ import ( ) func init() { + LoadModelsConfig() + NewEngine() + var err error orm, err = xorm.NewEngine("sqlite3", "./test.db") if err != nil { diff --git a/models/repo.go b/models/repo.go index 93f68ceddf..f252004785 100644 --- a/models/repo.go +++ b/models/repo.go @@ -41,10 +41,12 @@ var ( LanguageIgns, Licenses []string ) -func init() { +func LoadRepoConfig() { LanguageIgns = strings.Split(base.Cfg.MustValue("repository", "LANG_IGNS"), "|") Licenses = strings.Split(base.Cfg.MustValue("repository", "LICENSES"), "|") +} +func NewRepoContext() { zip.Verbose = false // Check if server has basic git setting. diff --git a/modules/base/conf.go b/modules/base/conf.go index 41b66b69f8..42d50da4f3 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -148,7 +148,7 @@ func newRegisterMailService() { log.Info("Register Mail Service Enabled") } -func init() { +func NewConfigContext() { var err error workDir, err := exeDir() if err != nil { diff --git a/modules/mailer/mailer.go b/modules/mailer/mailer.go index 150607f8c4..da63e01d2a 100644 --- a/modules/mailer/mailer.go +++ b/modules/mailer/mailer.go @@ -40,7 +40,7 @@ func (m Message) Content() string { var mailQueue chan *Message -func init() { +func NewMailerContext() { mailQueue = make(chan *Message, base.Cfg.MustInt("mailer", "SEND_BUFFER_LEN", 10)) go processMailQueue() } diff --git a/routers/admin/admin.go b/routers/admin/admin.go index a37f1207c9..1095a599b9 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -11,12 +11,14 @@ import ( func Dashboard(ctx *middleware.Context) { ctx.Data["Title"] = "Admin Dashboard" + ctx.Data["PageIsDashboard"] = true ctx.Data["Stats"] = models.GetStatistic() ctx.HTML(200, "admin/dashboard") } func Users(ctx *middleware.Context) { ctx.Data["Title"] = "User Management" + ctx.Data["PageIsUsers"] = true var err error ctx.Data["Users"], err = models.GetUsers(100, 0) @@ -29,6 +31,8 @@ func Users(ctx *middleware.Context) { func Repositories(ctx *middleware.Context) { ctx.Data["Title"] = "Repository Management" + ctx.Data["PageIsRepos"] = true + var err error ctx.Data["Repos"], err = models.GetRepos(100, 0) if err != nil { @@ -37,3 +41,9 @@ func Repositories(ctx *middleware.Context) { } ctx.HTML(200, "admin/repos") } + +func Config(ctx *middleware.Context) { + ctx.Data["Title"] = "Server Configuration" + ctx.Data["PageIsConfig"] = true + ctx.HTML(200, "admin/config") +} diff --git a/templates/admin/config.tmpl b/templates/admin/config.tmpl new file mode 100644 index 0000000000..d209bcdfd9 --- /dev/null +++ b/templates/admin/config.tmpl @@ -0,0 +1,17 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
+ {{template "admin/nav" .}} +
+
+
+ Server Configuration +
+ +
+ +
+
+
+
+{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/admin/dashboard.tmpl b/templates/admin/dashboard.tmpl index 6a914b65f7..8950f50cac 100644 --- a/templates/admin/dashboard.tmpl +++ b/templates/admin/dashboard.tmpl @@ -1,14 +1,7 @@ {{template "base/head" .}} {{template "base/navbar" .}}
- - + {{template "admin/nav" .}}
diff --git a/templates/admin/nav.tmpl b/templates/admin/nav.tmpl new file mode 100644 index 0000000000..bb704ee3fb --- /dev/null +++ b/templates/admin/nav.tmpl @@ -0,0 +1,8 @@ + \ No newline at end of file diff --git a/templates/admin/repos.tmpl b/templates/admin/repos.tmpl index f4834c9060..a1f41d8365 100644 --- a/templates/admin/repos.tmpl +++ b/templates/admin/repos.tmpl @@ -1,14 +1,7 @@ {{template "base/head" .}} {{template "base/navbar" .}}
- - + {{template "admin/nav" .}}
diff --git a/templates/admin/users.tmpl b/templates/admin/users.tmpl index b690e1771e..ae2b5bbb65 100644 --- a/templates/admin/users.tmpl +++ b/templates/admin/users.tmpl @@ -1,14 +1,7 @@ {{template "base/head" .}} {{template "base/navbar" .}}
- - + {{template "admin/nav" .}}
diff --git a/web.go b/web.go index a5a8305aee..648cb9d79c 100644 --- a/web.go +++ b/web.go @@ -16,9 +16,11 @@ import ( "github.com/gogits/binding" + "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/mailer" "github.com/gogits/gogs/modules/middleware" "github.com/gogits/gogs/routers" "github.com/gogits/gogs/routers/admin" @@ -36,6 +38,16 @@ gogs web`, Flags: []cli.Flag{}, } +// globalInit is for global configuration reload-able. +func globalInit() { + base.NewConfigContext() + mailer.NewMailerContext() + models.LoadModelsConfig() + models.LoadRepoConfig() + models.NewRepoContext() + models.NewEngine() +} + // Check run mode(Default of martini is Dev). func checkRunMode() { switch base.Cfg.MustValue("", "RUN_MODE") { @@ -59,6 +71,7 @@ func newMartini() *martini.ClassicMartini { } func runWeb(*cli.Context) { + globalInit() base.NewServices() checkRunMode() log.Info("%s %s", base.AppName, base.AppVer) @@ -101,9 +114,10 @@ func runWeb(*cli.Context) { m.Get("/help", routers.Help) adminReq := middleware.AdminRequire() - m.Any("/admin", reqSignIn, adminReq, admin.Dashboard) - m.Any("/admin/users", reqSignIn, adminReq, admin.Users) - m.Any("/admin/repos", reqSignIn, adminReq, admin.Repositories) + m.Get("/admin", reqSignIn, adminReq, admin.Dashboard) + m.Get("/admin/users", reqSignIn, adminReq, admin.Users) + m.Get("/admin/repos", reqSignIn, adminReq, admin.Repositories) + m.Get("/admin/config", reqSignIn, adminReq, admin.Config) m.Post("/:username/:reponame/settings", reqSignIn, middleware.RepoAssignment(true), repo.SettingPost) m.Get("/:username/:reponame/settings", reqSignIn, middleware.RepoAssignment(true), repo.Setting) -- cgit v1.2.3 From c1576b4c400376f22ec25012a6ca66e9c5539ee4 Mon Sep 17 00:00:00 2001 From: Unknown Date: Fri, 21 Mar 2014 03:27:59 -0400 Subject: Add admin add user --- models/models.go | 28 +++++++++---------- models/repo.go | 2 +- modules/base/conf.go | 2 ++ routers/admin/admin.go | 18 ++++++++++++ routers/admin/user.go | 63 ++++++++++++++++++++++++++++++++++++++++++ templates/admin/config.tmpl | 50 +++++++++++++++++++++++++++++++++ templates/admin/users.tmpl | 1 + templates/admin/users/new.tmpl | 54 ++++++++++++++++++++++++++++++++++++ web.go | 1 + 9 files changed, 204 insertions(+), 15 deletions(-) create mode 100644 routers/admin/user.go create mode 100644 templates/admin/users/new.tmpl (limited to 'models/repo.go') diff --git a/models/models.go b/models/models.go index bb0015d3de..a4550d7243 100644 --- a/models/models.go +++ b/models/models.go @@ -19,36 +19,36 @@ import ( var ( orm *xorm.Engine - dbCfg struct { + DbCfg struct { Type, Host, Name, User, Pwd, Path, SslMode string } ) func LoadModelsConfig() { - dbCfg.Type = base.Cfg.MustValue("database", "DB_TYPE") - dbCfg.Host = base.Cfg.MustValue("database", "HOST") - dbCfg.Name = base.Cfg.MustValue("database", "NAME") - dbCfg.User = base.Cfg.MustValue("database", "USER") - dbCfg.Pwd = base.Cfg.MustValue("database", "PASSWD") - dbCfg.Path = base.Cfg.MustValue("database", "PATH", "data/gogs.db") - dbCfg.SslMode = base.Cfg.MustValue("database", "SSL_MODE") + DbCfg.Type = base.Cfg.MustValue("database", "DB_TYPE") + DbCfg.Host = base.Cfg.MustValue("database", "HOST") + DbCfg.Name = base.Cfg.MustValue("database", "NAME") + DbCfg.User = base.Cfg.MustValue("database", "USER") + DbCfg.Pwd = base.Cfg.MustValue("database", "PASSWD") + DbCfg.SslMode = base.Cfg.MustValue("database", "SSL_MODE") + DbCfg.Path = base.Cfg.MustValue("database", "PATH", "data/gogs.db") } func setEngine() { var err error - switch dbCfg.Type { + switch DbCfg.Type { case "mysql": orm, err = xorm.NewEngine("mysql", fmt.Sprintf("%s:%s@%s/%s?charset=utf8", - dbCfg.User, dbCfg.Pwd, dbCfg.Host, dbCfg.Name)) + DbCfg.User, DbCfg.Pwd, DbCfg.Host, DbCfg.Name)) case "postgres": orm, err = xorm.NewEngine("postgres", fmt.Sprintf("user=%s password=%s dbname=%s sslmode=%s", - dbCfg.User, dbCfg.Pwd, dbCfg.Name, dbCfg.SslMode)) + DbCfg.User, DbCfg.Pwd, DbCfg.Name, DbCfg.SslMode)) case "sqlite3": - os.MkdirAll(path.Dir(dbCfg.Path), os.ModePerm) - orm, err = xorm.NewEngine("sqlite3", dbCfg.Path) + os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm) + orm, err = xorm.NewEngine("sqlite3", DbCfg.Path) default: - fmt.Printf("Unknown database type: %s\n", dbCfg.Type) + fmt.Printf("Unknown database type: %s\n", DbCfg.Type) os.Exit(2) } if err != nil { diff --git a/models/repo.go b/models/repo.go index f252004785..918e5dc84c 100644 --- a/models/repo.go +++ b/models/repo.go @@ -107,7 +107,7 @@ func IsRepositoryExist(user *User, repoName string) (bool, error) { var ( // Define as all lower case!! - illegalPatterns = []string{"[.][Gg][Ii][Tt]", "user", "help", "stars", "issues", "pulls", "commits", "admin", "repo", "template"} + illegalPatterns = []string{"[.][Gg][Ii][Tt]", "user", "help", "stars", "issues", "pulls", "commits", "admin", "repo", "template", "admin"} ) // IsLegalName returns false if name contains illegal characters. diff --git a/modules/base/conf.go b/modules/base/conf.go index 3050b915fa..bf054ec3c5 100644 --- a/modules/base/conf.go +++ b/modules/base/conf.go @@ -32,6 +32,7 @@ var ( AppUrl string Domain string SecretKey string + RunUser string RepoRootPath string Cfg *goconfig.ConfigFile @@ -179,6 +180,7 @@ func NewConfigContext() { AppUrl = Cfg.MustValue("server", "ROOT_URL") Domain = Cfg.MustValue("server", "DOMAIN") SecretKey = Cfg.MustValue("security", "SECRET_KEY") + RunUser = Cfg.MustValue("", "RUN_USER") // Determine and create root git reposiroty path. RepoRootPath = Cfg.MustValue("repository", "ROOT") diff --git a/routers/admin/admin.go b/routers/admin/admin.go index 1095a599b9..547883f7bc 100644 --- a/routers/admin/admin.go +++ b/routers/admin/admin.go @@ -5,7 +5,12 @@ package admin import ( + "strings" + + "github.com/codegangsta/martini" + "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/base" "github.com/gogits/gogs/modules/middleware" ) @@ -45,5 +50,18 @@ func Repositories(ctx *middleware.Context) { func Config(ctx *middleware.Context) { ctx.Data["Title"] = "Server Configuration" ctx.Data["PageIsConfig"] = true + + ctx.Data["AppUrl"] = base.AppUrl + ctx.Data["Domain"] = base.Domain + ctx.Data["RunUser"] = base.RunUser + ctx.Data["RunMode"] = strings.Title(martini.Env) + ctx.Data["RepoRootPath"] = base.RepoRootPath + + ctx.Data["Service"] = base.Service + + ctx.Data["DbCfg"] = models.DbCfg + + ctx.Data["Mailer"] = base.MailService + ctx.HTML(200, "admin/config") } diff --git a/routers/admin/user.go b/routers/admin/user.go new file mode 100644 index 0000000000..9dcc1499e3 --- /dev/null +++ b/routers/admin/user.go @@ -0,0 +1,63 @@ +// Copyright 2014 The Gogs Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package admin + +import ( + "strings" + + "github.com/gogits/gogs/models" + "github.com/gogits/gogs/modules/auth" + "github.com/gogits/gogs/modules/log" + "github.com/gogits/gogs/modules/middleware" +) + +func NewUser(ctx *middleware.Context, form auth.RegisterForm) { + ctx.Data["Title"] = "New Account" + + if ctx.Req.Method == "GET" { + ctx.HTML(200, "admin/users/new") + return + } + + if form.Password != form.RetypePasswd { + ctx.Data["HasError"] = true + ctx.Data["Err_Password"] = true + ctx.Data["Err_RetypePasswd"] = true + ctx.Data["ErrorMsg"] = "Password and re-type password are not same" + auth.AssignForm(form, ctx.Data) + } + + if ctx.HasError() { + ctx.HTML(200, "admin/users/new") + return + } + + u := &models.User{ + Name: form.UserName, + Email: form.Email, + Passwd: form.Password, + IsActive: true, + } + + var err error + if u, err = models.RegisterUser(u); err != nil { + switch err { + case models.ErrUserAlreadyExist: + ctx.RenderWithErr("Username has been already taken", "admin/users/new", &form) + case models.ErrEmailAlreadyUsed: + ctx.RenderWithErr("E-mail address has been already used", "admin/users/new", &form) + case models.ErrUserNameIllegal: + ctx.RenderWithErr(models.ErrRepoNameIllegal.Error(), "admin/users/new", &form) + default: + ctx.Handle(200, "admin.user.NewUser", err) + } + return + } + + log.Trace("%s User created by admin(%s): %s", ctx.Req.RequestURI, + ctx.User.LowerName, strings.ToLower(form.UserName)) + + ctx.Redirect("/admin/users") +} diff --git a/templates/admin/config.tmpl b/templates/admin/config.tmpl index d209bcdfd9..9593a545f8 100644 --- a/templates/admin/config.tmpl +++ b/templates/admin/config.tmpl @@ -9,7 +9,57 @@
+
Application Name: {{AppName}}
+
Application Version: {{AppVer}}
+
Application URL: {{.AppUrl}}
+
Domain: {{.Domain}}
+
+
Run User: {{.RunUser}}
+
Run Mode: {{.RunMode}}
+
+
Repository Root Path: {{.RepoRootPath}}
+
+
+ +
+
+ Database Configuration +
+
+
Type: {{.DbCfg.Type}}
+
Host: {{.DbCfg.Host}}
+
Name: {{.DbCfg.Name}}
+
User: {{.DbCfg.User}}
+
SslMode: {{.DbCfg.SslMode}} (for "postgres" only)
+
Path: {{.DbCfg.Path}} (for "sqlite3" only)
+
+
+ +
+
+ Service Configuration +
+ +
+
Register Email Confirmation:
+
Disenable Registeration:
+
Require Sign In View:
+
+
Active Code Lives: {{.Service.ActiveCodeLives}} minutes
+
Reset Password Code Lives: {{.Service.ResetPwdCodeLives}} minutes
+
+
+ +
+
+ Mailer Configuration +
+ +
+
Name: {{.Mailer.Name}}
+
Host: {{.Mailer.Host}}
+
User: {{.Mailer.User}}
diff --git a/templates/admin/users.tmpl b/templates/admin/users.tmpl index ae2b5bbb65..d82f04b812 100644 --- a/templates/admin/users.tmpl +++ b/templates/admin/users.tmpl @@ -9,6 +9,7 @@
+ New Account diff --git a/templates/admin/users/new.tmpl b/templates/admin/users/new.tmpl new file mode 100644 index 0000000000..bf59b16a80 --- /dev/null +++ b/templates/admin/users/new.tmpl @@ -0,0 +1,54 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +
+ {{template "admin/nav" .}} +
+
+
+ New Account +
+ +
+
+
+
{{.ErrorMsg}}
+
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+ +
+ +
+
+ +
+
+ +
+
+ +
+
+ +
+
+{{template "base/footer" .}} \ No newline at end of file diff --git a/web.go b/web.go index 6fe838aa78..d6d78afa5d 100644 --- a/web.go +++ b/web.go @@ -117,6 +117,7 @@ func runWeb(*cli.Context) { adminReq := middleware.AdminRequire() m.Get("/admin", reqSignIn, adminReq, admin.Dashboard) m.Get("/admin/users", reqSignIn, adminReq, admin.Users) + m.Any("/admin/users/new", reqSignIn, adminReq, binding.BindIgnErr(auth.RegisterForm{}), admin.NewUser) m.Get("/admin/repos", reqSignIn, adminReq, admin.Repositories) m.Get("/admin/config", reqSignIn, adminReq, admin.Config) -- cgit v1.2.3