1
0
mirror of https://github.com/go-gitea/gitea.git synced 2024-12-04 14:46:57 -05:00

Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Meaglith Ma 2014-04-06 17:28:33 +08:00
commit 2e8d5c2eb3
42 changed files with 1315 additions and 170 deletions

View File

@ -19,6 +19,9 @@ github.com/gogits/gfm=
github.com/gogits/cache=
github.com/gogits/session=
github.com/gogits/webdav=
github.com/martini-contrib/oauth2=
github.com/martini-contrib/sessions=
code.google.com/p/goauth2=
[res]
include=templates|public|conf

View File

@ -30,10 +30,10 @@ More importantly, Gogs only needs one binary to setup your own project hosting o
- Activity timeline
- SSH/HTTPS(Clone only) protocol support.
- Register/delete account.
- Create/delete/watch public repository.
- User profile page.
- Register/delete/rename account.
- Create/delete/watch/rename public repository.
- Repository viewer.
- Issue tracker.
- Gravatar and cache support.
- Mail service(register, issue).
- Administration panel.
@ -59,7 +59,7 @@ There are two ways to install Gogs:
## Contributors
This project was launched by [Unknown](https://github.com/Unknwon) and [lunny](https://github.com/lunny); [fuxiaohei](https://github.com/fuxiaohei) and [slene](https://github.com/slene) joined the team soon after. See [contributors page](https://github.com/gogits/gogs/graphs/contributors) for full list of contributors.
This project was launched by [Unknown](https://github.com/Unknwon) and [lunny](https://github.com/lunny); [fuxiaohei](https://github.com/fuxiaohei), [slene](https://github.com/slene) and [skyblue](https://github.com/shxsun) joined the team soon after. See [contributors page](https://github.com/gogits/gogs/graphs/contributors) for full list of contributors.
## License

View File

@ -24,10 +24,10 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依
- 活动时间线
- SSH/HTTPS仅限 Clone 协议支持
- 注册/删除用户
- 创建/删除/关注公开仓库
- 用户个人信息页面
- 注册/删除/重命名用户
- 创建/删除/关注/重命名公开仓库
- 仓库浏览器
- Bug 追踪系统
- Gravatar 以及缓存支持
- 邮件服务注册、Issue
- 管理员面板
@ -53,7 +53,7 @@ Gogs 完全使用 Go 语言来实现对 Git 数据的操作,实现 **零** 依
## 贡献成员
本项目最初由 [Unknown](https://github.com/Unknwon) 和 [lunny](https://github.com/lunny) 发起,随后 [fuxiaohei](https://github.com/fuxiaohei) 与 [slene](https://github.com/slene) 加入到开发团队。您可以通过查看 [贡献者页面](https://github.com/gogits/gogs/graphs/contributors) 获取完整的贡献者列表。
本项目最初由 [Unknown](https://github.com/Unknwon) 和 [lunny](https://github.com/lunny) 发起,随后 [fuxiaohei](https://github.com/fuxiaohei)、[slene](https://github.com/slene) 以及 [skyblue](https://github.com/shxsun) 加入到开发团队。您可以通过查看 [贡献者页面](https://github.com/gogits/gogs/graphs/contributors) 获取完整的贡献者列表。
## 授权许可

View File

@ -19,7 +19,7 @@ import (
// Test that go1.2 tag above is included in builds. main.go refers to this definition.
const go12tag = true
const APP_VER = "0.2.0.0330 Alpha"
const APP_VER = "0.2.0.0403 Alpha"
func init() {
base.AppVer = APP_VER

View File

@ -32,6 +32,14 @@ func AddAccess(access *Access) error {
return err
}
// UpdateAccess updates access information.
func UpdateAccess(access *Access) error {
access.UserName = strings.ToLower(access.UserName)
access.RepoName = strings.ToLower(access.RepoName)
_, err := orm.Id(access.Id).Update(access)
return err
}
// HasAccess returns true if someone can read or write to given repository.
func HasAccess(userName, repoName string, mode int) (bool, error) {
return orm.Get(&Access{

View File

@ -21,6 +21,7 @@ const (
OP_COMMIT_REPO
OP_CREATE_ISSUE
OP_PULL_REQUEST
OP_TRANSFER_REPO
)
// Action represents user operation type and other information to repository.,
@ -108,6 +109,18 @@ func NewRepoAction(user *User, repo *Repository) (err error) {
return err
}
// TransferRepoAction adds new action for transfering repository.
func TransferRepoAction(user, newUser *User, repo *Repository) (err error) {
if err = NotifyWatchers(&Action{ActUserId: user.Id, ActUserName: user.Name, ActEmail: user.Email,
OpType: OP_TRANSFER_REPO, RepoId: repo.Id, RepoName: repo.Name, Content: newUser.Name}); err != nil {
log.Error("action.TransferRepoAction(notify watchers): %d/%s", user.Id, repo.Name)
return err
}
log.Trace("action.TransferRepoAction: %s/%s", user.LowerName, repo.LowerName)
return err
}
// GetFeeds returns action list of given user in given context.
func GetFeeds(userid, offset int64, isProfile bool) ([]Action, error) {
actions := make([]Action, 0, 20)

View File

@ -56,6 +56,25 @@ func GetBranches(userName, repoName string) ([]string, error) {
return brs, nil
}
// GetTags returns all tags of given repository.
func GetTags(userName, repoName string) ([]string, error) {
repo, err := git.OpenRepository(RepoPath(userName, repoName))
if err != nil {
return nil, err
}
refs, err := repo.AllTags()
if err != nil {
return nil, err
}
tags := make([]string, len(refs))
for i, ref := range refs {
tags[i] = ref.Name
}
return tags, nil
}
func IsBranchExist(userName, repoName, branchName string) bool {
repo, err := git.OpenRepository(RepoPath(userName, repoName))
if err != nil {

View File

@ -53,10 +53,10 @@ func NewTestEngine(x *xorm.Engine) (err error) {
// os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
// x, err = xorm.NewEngine("sqlite3", DbCfg.Path)
default:
return fmt.Errorf("Unknown database type: %s\n", DbCfg.Type)
return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
}
if err != nil {
return fmt.Errorf("models.init(fail to conntect database): %v\n", err)
return fmt.Errorf("models.init(fail to conntect database): %v", err)
}
return x.Sync(new(User), new(PublicKey), new(Repository), new(Watch),
@ -75,10 +75,10 @@ func SetEngine() (err error) {
os.MkdirAll(path.Dir(DbCfg.Path), os.ModePerm)
orm, err = xorm.NewEngine("sqlite3", DbCfg.Path)
default:
return fmt.Errorf("Unknown database type: %s\n", DbCfg.Type)
return fmt.Errorf("Unknown database type: %s", DbCfg.Type)
}
if err != nil {
return fmt.Errorf("models.init(fail to conntect database): %v\n", err)
return fmt.Errorf("models.init(fail to conntect database): %v", err)
}
// WARNNING: for serv command, MUST remove the output to os.stdout,
@ -89,7 +89,7 @@ func SetEngine() (err error) {
f, err := os.Create(logPath)
if err != nil {
return fmt.Errorf("models.init(fail to create xorm.log): %v\n", err)
return fmt.Errorf("models.init(fail to create xorm.log): %v", err)
}
orm.Logger = f
@ -104,7 +104,7 @@ func NewEngine() (err error) {
return err
} else if err = orm.Sync(new(User), new(PublicKey), new(Repository), new(Watch),
new(Action), new(Access), new(Issue), new(Comment)); err != nil {
return fmt.Errorf("sync database struct error: %v\n", err)
return fmt.Errorf("sync database struct error: %v", err)
}
return nil
}

18
models/oauth2.go Normal file
View File

@ -0,0 +1,18 @@
package models
import "time"
// OT: Oauth2 Type
const (
OT_GITHUB = iota + 1
OT_GOOGLE
OT_TWITTER
)
type Oauth2 struct {
Uid int64 `xorm:"pk"` // userId
Type int `xorm:"pk unique(oauth)"` // twitter,github,google...
Identity string `xorm:"pk unique(oauth)"` // id..
Token string `xorm:"VARCHAR(200) not null"`
RefreshTime time.Time `xorm:"created"`
}

View File

@ -77,8 +77,8 @@ func init() {
// PublicKey represents a SSH key of user.
type PublicKey struct {
Id int64
OwnerId int64 `xorm:"index"`
Name string `xorm:"unique not null"`
OwnerId int64 `xorm:" index not null"`
Name string `xorm:" not null"` //UNIQUE(s)
Fingerprint string
Content string `xorm:"TEXT not null"`
Created time.Time `xorm:"created"`

View File

@ -74,6 +74,7 @@ type Repository struct {
NumStars int
NumForks int
NumIssues int
NumReleases int `xorm:"NOT NULL"`
NumClosedIssues int
NumOpenIssues int `xorm:"-"`
IsPrivate bool
@ -142,17 +143,17 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv
if err = initRepository(repoPath, user, repo, initReadme, repoLang, license); err != nil {
return nil, err
}
session := orm.NewSession()
defer session.Close()
session.Begin()
sess := orm.NewSession()
defer sess.Close()
sess.Begin()
if _, err = session.Insert(repo); err != nil {
if _, err = sess.Insert(repo); err != nil {
if err2 := os.RemoveAll(repoPath); err2 != nil {
log.Error("repo.CreateRepository(repo): %v", err)
return nil, errors.New(fmt.Sprintf(
"delete repo directory %s/%s failed(1): %v", user.Name, repoName, err2))
}
session.Rollback()
sess.Rollback()
return nil, err
}
@ -161,8 +162,8 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv
RepoName: strings.ToLower(path.Join(user.Name, repo.Name)),
Mode: AU_WRITABLE,
}
if _, err = session.Insert(&access); err != nil {
session.Rollback()
if _, err = sess.Insert(&access); err != nil {
sess.Rollback()
if err2 := os.RemoveAll(repoPath); err2 != nil {
log.Error("repo.CreateRepository(access): %v", err)
return nil, errors.New(fmt.Sprintf(
@ -172,8 +173,8 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv
}
rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
if _, err = session.Exec(rawSql, user.Id); err != nil {
session.Rollback()
if _, err = sess.Exec(rawSql, user.Id); err != nil {
sess.Rollback()
if err2 := os.RemoveAll(repoPath); err2 != nil {
log.Error("repo.CreateRepository(repo count): %v", err)
return nil, errors.New(fmt.Sprintf(
@ -182,8 +183,8 @@ func CreateRepository(user *User, repoName, desc, repoLang, license string, priv
return nil, err
}
if err = session.Commit(); err != nil {
session.Rollback()
if err = sess.Commit(); err != nil {
sess.Rollback()
if err2 := os.RemoveAll(repoPath); err2 != nil {
log.Error("repo.CreateRepository(commit): %v", err)
return nil, errors.New(fmt.Sprintf(
@ -368,14 +369,86 @@ func RepoPath(userName, repoName string) string {
return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git")
}
// TransferOwnership transfers all corresponding setting from old user to new one.
func TransferOwnership(user *User, newOwner string, repo *Repository) (err error) {
newUser, err := GetUserByName(newOwner)
if err != nil {
return err
}
// Update accesses.
accesses := make([]Access, 0, 10)
if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repo.LowerName}); err != nil {
return err
}
for i := range accesses {
accesses[i].RepoName = newUser.LowerName + "/" + repo.LowerName
if accesses[i].UserName == user.LowerName {
accesses[i].UserName = newUser.LowerName
}
if err = UpdateAccess(&accesses[i]); err != nil {
return err
}
}
// Update repository.
repo.OwnerId = newUser.Id
if _, err := orm.Id(repo.Id).Update(repo); err != nil {
return err
}
// Update user repository number.
rawSql := "UPDATE `user` SET num_repos = num_repos + 1 WHERE id = ?"
if _, err = orm.Exec(rawSql, newUser.Id); err != nil {
return err
}
rawSql = "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
if _, err = orm.Exec(rawSql, user.Id); err != nil {
return err
}
// Add watch of new owner to repository.
if !IsWatching(newUser.Id, repo.Id) {
if err = WatchRepo(newUser.Id, repo.Id, true); err != nil {
return err
}
}
if err = TransferRepoAction(user, newUser, repo); err != nil {
return err
}
// Change repository directory name.
return os.Rename(RepoPath(user.Name, repo.Name), RepoPath(newUser.Name, repo.Name))
}
// ChangeRepositoryName changes all corresponding setting from old repository name to new one.
func ChangeRepositoryName(userName, oldRepoName, newRepoName string) (err error) {
// Update accesses.
accesses := make([]Access, 0, 10)
if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil {
return err
}
for i := range accesses {
accesses[i].RepoName = userName + "/" + newRepoName
if err = UpdateAccess(&accesses[i]); err != nil {
return err
}
}
// Change repository directory name.
return os.Rename(RepoPath(userName, oldRepoName), RepoPath(userName, newRepoName))
}
func UpdateRepository(repo *Repository) error {
repo.LowerName = strings.ToLower(repo.Name)
if len(repo.Description) > 255 {
repo.Description = repo.Description[:255]
}
if len(repo.Website) > 255 {
repo.Website = repo.Website[:255]
}
_, err := orm.Id(repo.Id).AllCols().Update(repo)
return err
}
@ -390,29 +463,30 @@ func DeleteRepository(userId, repoId int64, userName string) (err error) {
return ErrRepoNotExist
}
session := orm.NewSession()
if err = session.Begin(); err != nil {
sess := orm.NewSession()
defer sess.Close()
if err = sess.Begin(); err != nil {
return err
}
if _, err = session.Delete(&Repository{Id: repoId}); err != nil {
session.Rollback()
if _, err = sess.Delete(&Repository{Id: repoId}); err != nil {
sess.Rollback()
return err
}
if _, err := session.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
session.Rollback()
if _, err := sess.Delete(&Access{RepoName: strings.ToLower(path.Join(userName, repo.Name))}); err != nil {
sess.Rollback()
return err
}
rawSql := "UPDATE `user` SET num_repos = num_repos - 1 WHERE id = ?"
if _, err = session.Exec(rawSql, userId); err != nil {
session.Rollback()
if _, err = sess.Exec(rawSql, userId); err != nil {
sess.Rollback()
return err
}
if _, err = session.Delete(&Watch{RepoId: repoId}); err != nil {
session.Rollback()
if _, err = sess.Delete(&Watch{RepoId: repoId}); err != nil {
sess.Rollback()
return err
}
if err = session.Commit(); err != nil {
session.Rollback()
if err = sess.Commit(); err != nil {
sess.Rollback()
return err
}
if err = os.RemoveAll(RepoPath(userName, repo.Name)); err != nil {
@ -513,6 +587,7 @@ func NotifyWatchers(act *Action) error {
continue
}
act.Id = 0
act.UserId = watches[i].UserId
if _, err = orm.InsertOne(act); err != nil {
return errors.New("repo.NotifyWatchers(create action): " + err.Error())

View File

@ -105,11 +105,17 @@ type Member struct {
// IsUserExist checks if given user name exist,
// the user name should be noncased unique.
func IsUserExist(name string) (bool, error) {
if len(name) == 0 {
return false, nil
}
return orm.Get(&User{LowerName: strings.ToLower(name)})
}
// IsEmailUsed returns true if the e-mail has been used.
func IsEmailUsed(email string) (bool, error) {
if len(email) == 0 {
return false, nil
}
return orm.Get(&User{Email: email})
}
@ -203,8 +209,52 @@ func VerifyUserActiveCode(code string) (user *User) {
return nil
}
// ChangeUserName changes all corresponding setting from old user name to new one.
func ChangeUserName(user *User, newUserName string) (err error) {
newUserName = strings.ToLower(newUserName)
// Update accesses of user.
accesses := make([]Access, 0, 10)
if err = orm.Find(&accesses, &Access{UserName: user.LowerName}); err != nil {
return err
}
for i := range accesses {
accesses[i].UserName = newUserName
if strings.HasPrefix(accesses[i].RepoName, user.LowerName+"/") {
accesses[i].RepoName = strings.Replace(accesses[i].RepoName, user.LowerName, newUserName, 1)
if err = UpdateAccess(&accesses[i]); err != nil {
return err
}
}
}
repos, err := GetRepositories(user)
if err != nil {
return err
}
for i := range repos {
accesses = make([]Access, 0, 10)
// Update accesses of user repository.
if err = orm.Find(&accesses, &Access{RepoName: user.LowerName + "/" + repos[i].LowerName}); err != nil {
return err
}
for j := range accesses {
accesses[j].RepoName = newUserName + "/" + repos[i].LowerName
if err = UpdateAccess(&accesses[j]); err != nil {
return err
}
}
}
// Change user directory name.
return os.Rename(UserPath(user.LowerName), UserPath(newUserName))
}
// UpdateUser updates user's information.
func UpdateUser(user *User) (err error) {
user.LowerName = strings.ToLower(user.Name)
if len(user.Location) > 255 {
user.Location = user.Location[:255]
}
@ -233,6 +283,11 @@ func DeleteUser(user *User) error {
return err
}
// Delete all accesses.
if _, err = orm.Delete(&Access{UserName: user.LowerName}); err != nil {
return err
}
// Delete all SSH keys.
keys := make([]PublicKey, 0, 10)
if err = orm.Find(&keys, &PublicKey{OwnerId: user.Id}); err != nil {

View File

@ -75,6 +75,7 @@ type FeedsForm struct {
}
type UpdateProfileForm struct {
UserName string `form:"username" binding:"Required;AlphaDash;MaxSize(30)"`
Email string `form:"email" binding:"Required;Email;MaxSize(50)"`
Website string `form:"website" binding:"MaxSize(50)"`
Location string `form:"location" binding:"MaxSize(50)"`
@ -83,6 +84,7 @@ type UpdateProfileForm struct {
func (f *UpdateProfileForm) Name(field string) string {
names := map[string]string{
"UserName": "Username",
"Email": "E-mail address",
"Website": "Website",
"Location": "Location",

View File

@ -494,6 +494,8 @@ func ActionIcon(opType int) string {
return "arrow-circle-o-right"
case 6: // Create issue.
return "exclamation-circle"
case 8: // Transfer repository.
return "share"
default:
return "invalid type"
}
@ -503,8 +505,9 @@ const (
TPL_CREATE_REPO = `<a href="/user/%s">%s</a> created repository <a href="/%s">%s</a>`
TPL_COMMIT_REPO = `<a href="/user/%s">%s</a> pushed to <a href="/%s/src/%s">%s</a> at <a href="/%s">%s</a>%s`
TPL_COMMIT_REPO_LI = `<div><img src="%s?s=16" alt="user-avatar"/> <a href="/%s/commit/%s">%s</a> %s</div>`
TPL_CREATE_Issue = `<a href="/user/%s">%s</a> opened issue <a href="/%s/issues/%s">%s#%s</a>
TPL_CREATE_ISSUE = `<a href="/user/%s">%s</a> opened issue <a href="/%s/issues/%s">%s#%s</a>
<div><img src="%s?s=16" alt="user-avatar"/> %s</div>`
TPL_TRANSFER_REPO = `<a href="/user/%s">%s</a> transfered repository <code>%s</code> to <a href="/%s">%s</a>`
)
type PushCommit struct {
@ -547,8 +550,11 @@ func ActionDesc(act Actioner) string {
buf.String())
case 6: // Create issue.
infos := strings.SplitN(content, "|", 2)
return fmt.Sprintf(TPL_CREATE_Issue, actUserName, actUserName, repoLink, infos[0], repoLink, infos[0],
return fmt.Sprintf(TPL_CREATE_ISSUE, actUserName, actUserName, repoLink, infos[0], repoLink, infos[0],
AvatarLink(email), infos[1])
case 8: // Transfer repository.
newRepoLink := content + "/" + repoName
return fmt.Sprintf(TPL_TRANSFER_REPO, actUserName, actUserName, repoLink, newRepoLink, newRepoLink)
default:
return "invalid type"
}

View File

@ -15,7 +15,7 @@ var (
)
func init() {
NewLogger(10000, "console", `{"level": 0}`)
NewLogger(0, "console", `{"level": 0}`)
}
func NewLogger(bufLen int64, mode, config string) {

View File

@ -92,8 +92,8 @@ func SendActiveMail(r *middleware.Render, user *models.User) {
}
// SendNotifyMail sends mail notification of all watchers.
func SendNotifyMail(userId, repoId int64, userName, repoName, subject, content string) error {
watches, err := models.GetWatches(repoId)
func SendNotifyMail(user, owner *models.User, repo *models.Repository, issue *models.Issue) error {
watches, err := models.GetWatches(repo.Id)
if err != nil {
return errors.New("mail.NotifyWatchers(get watches): " + err.Error())
}
@ -101,7 +101,7 @@ func SendNotifyMail(userId, repoId int64, userName, repoName, subject, content s
tos := make([]string, 0, len(watches))
for i := range watches {
uid := watches[i].UserId
if userId == uid {
if user.Id == uid {
continue
}
u, err := models.GetUserById(uid)
@ -115,7 +115,10 @@ func SendNotifyMail(userId, repoId int64, userName, repoName, subject, content s
return nil
}
msg := NewMailMessageFrom(tos, userName, subject, content)
subject := fmt.Sprintf("[%s] %s", repo.Name, issue.Name)
content := fmt.Sprintf("%s<br>-<br> <a href=\"%s%s/%s/issues/%d\">View it on Gogs</a>.",
issue.Content, base.AppUrl, owner.Name, repo.Name, issue.Index)
msg := NewMailMessageFrom(tos, user.Name, subject, content)
msg.Info = fmt.Sprintf("Subject: %s, send notify emails", subject)
SendAsync(&msg)
return nil

View File

@ -90,7 +90,9 @@ func (ctx *Context) HTML(status int, name string, htmlOpt ...HTMLOptions) {
func (ctx *Context) RenderWithErr(msg, tpl string, form auth.Form) {
ctx.Data["HasError"] = true
ctx.Data["ErrorMsg"] = msg
if form != nil {
auth.AssignForm(form, ctx.Data)
}
ctx.HTML(200, tpl)
}

View File

@ -79,6 +79,7 @@ func RepoAssignment(redirect bool, args ...bool) martini.Handler {
ctx.Handle(404, "RepoAssignment", err)
return
}
repo.NumOpenIssues = repo.NumIssues - repo.NumClosedIssues
ctx.Repo.Repository = repo
ctx.Data["IsBareRepo"] = ctx.Repo.Repository.IsBare

233
modules/oauth2/oauth2.go Normal file
View File

@ -0,0 +1,233 @@
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package oauth2 contains Martini handlers to provide
// user login via an OAuth 2.0 backend.
package oauth2
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
"time"
"code.google.com/p/goauth2/oauth"
"github.com/go-martini/martini"
"github.com/martini-contrib/sessions"
)
const (
codeRedirect = 302
keyToken = "oauth2_token"
keyNextPage = "next"
)
var (
// Path to handle OAuth 2.0 logins.
PathLogin = "/login"
// Path to handle OAuth 2.0 logouts.
PathLogout = "/logout"
// Path to handle callback from OAuth 2.0 backend
// to exchange credentials.
PathCallback = "/oauth2callback"
// Path to handle error cases.
PathError = "/oauth2error"
)
// Represents OAuth2 backend options.
type Options struct {
ClientId string
ClientSecret string
RedirectURL string
Scopes []string
AuthUrl string
TokenUrl string
}
// Represents a container that contains
// user's OAuth 2.0 access and refresh tokens.
type Tokens interface {
Access() string
Refresh() string
IsExpired() bool
ExpiryTime() time.Time
ExtraData() map[string]string
}
type token struct {
oauth.Token
}
func (t *token) ExtraData() map[string]string {
return t.Extra
}
// Returns the access token.
func (t *token) Access() string {
return t.AccessToken
}
// Returns the refresh token.
func (t *token) Refresh() string {
return t.RefreshToken
}
// Returns whether the access token is
// expired or not.
func (t *token) IsExpired() bool {
if t == nil {
return true
}
return t.Expired()
}
// Returns the expiry time of the user's
// access token.
func (t *token) ExpiryTime() time.Time {
return t.Expiry
}
// Formats tokens into string.
func (t *token) String() string {
return fmt.Sprintf("tokens: %v", t)
}
// Returns a new Google OAuth 2.0 backend endpoint.
func Google(opts *Options) martini.Handler {
opts.AuthUrl = "https://accounts.google.com/o/oauth2/auth"
opts.TokenUrl = "https://accounts.google.com/o/oauth2/token"
return NewOAuth2Provider(opts)
}
// Returns a new Github OAuth 2.0 backend endpoint.
func Github(opts *Options) martini.Handler {
opts.AuthUrl = "https://github.com/login/oauth/authorize"
opts.TokenUrl = "https://github.com/login/oauth/access_token"
return NewOAuth2Provider(opts)
}
func Facebook(opts *Options) martini.Handler {
opts.AuthUrl = "https://www.facebook.com/dialog/oauth"
opts.TokenUrl = "https://graph.facebook.com/oauth/access_token"
return NewOAuth2Provider(opts)
}
// Returns a generic OAuth 2.0 backend endpoint.
func NewOAuth2Provider(opts *Options) martini.Handler {
config := &oauth.Config{
ClientId: opts.ClientId,
ClientSecret: opts.ClientSecret,
RedirectURL: opts.RedirectURL,
Scope: strings.Join(opts.Scopes, " "),
AuthURL: opts.AuthUrl,
TokenURL: opts.TokenUrl,
}
transport := &oauth.Transport{
Config: config,
Transport: http.DefaultTransport,
}
return func(s sessions.Session, c martini.Context, w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
switch r.URL.Path {
case PathLogin:
login(transport, s, w, r)
case PathLogout:
logout(transport, s, w, r)
case PathCallback:
handleOAuth2Callback(transport, s, w, r)
}
}
tk := unmarshallToken(s)
if tk != nil {
// check if the access token is expired
if tk.IsExpired() && tk.Refresh() == "" {
s.Delete(keyToken)
tk = nil
}
}
// Inject tokens.
c.MapTo(tk, (*Tokens)(nil))
}
}
// Handler that redirects user to the login page
// if user is not logged in.
// Sample usage:
// m.Get("/login-required", oauth2.LoginRequired, func() ... {})
var LoginRequired martini.Handler = func() martini.Handler {
return func(s sessions.Session, c martini.Context, w http.ResponseWriter, r *http.Request) {
token := unmarshallToken(s)
if token == nil || token.IsExpired() {
next := url.QueryEscape(r.URL.RequestURI())
http.Redirect(w, r, PathLogin+"?next="+next, codeRedirect)
}
}
}()
func login(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
next := extractPath(r.URL.Query().Get(keyNextPage))
if s.Get(keyToken) == nil {
// User is not logged in.
http.Redirect(w, r, t.Config.AuthCodeURL(next), codeRedirect)
return
}
// No need to login, redirect to the next page.
http.Redirect(w, r, next, codeRedirect)
}
func logout(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
next := extractPath(r.URL.Query().Get(keyNextPage))
s.Delete(keyToken)
http.Redirect(w, r, next, codeRedirect)
}
func handleOAuth2Callback(t *oauth.Transport, s sessions.Session, w http.ResponseWriter, r *http.Request) {
next := extractPath(r.URL.Query().Get("state"))
code := r.URL.Query().Get("code")
tk, err := t.Exchange(code)
if err != nil {
// Pass the error message, or allow dev to provide its own
// error handler.
http.Redirect(w, r, PathError, codeRedirect)
return
}
// Store the credentials in the session.
val, _ := json.Marshal(tk)
s.Set(keyToken, val)
http.Redirect(w, r, next, codeRedirect)
}
func unmarshallToken(s sessions.Session) (t *token) {
if s.Get(keyToken) == nil {
return
}
data := s.Get(keyToken).([]byte)
var tk oauth.Token
json.Unmarshal(data, &tk)
return &token{tk}
}
func extractPath(next string) string {
n, err := url.Parse(next)
if err != nil {
return "/"
}
return n.Path
}

View File

@ -0,0 +1,162 @@
// Copyright 2014 Google Inc. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package oauth2
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/go-martini/martini"
"github.com/martini-contrib/sessions"
)
func Test_LoginRedirect(t *testing.T) {
recorder := httptest.NewRecorder()
m := martini.New()
m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
m.Use(Google(&Options{
ClientId: "client_id",
ClientSecret: "client_secret",
RedirectURL: "refresh_url",
Scopes: []string{"x", "y"},
}))
r, _ := http.NewRequest("GET", "/login", nil)
m.ServeHTTP(recorder, r)
location := recorder.HeaderMap["Location"][0]
if recorder.Code != 302 {
t.Errorf("Not being redirected to the auth page.")
}
if location != "https://accounts.google.com/o/oauth2/auth?access_type=&approval_prompt=&client_id=client_id&redirect_uri=refresh_url&response_type=code&scope=x+y&state=" {
t.Errorf("Not being redirected to the right page, %v found", location)
}
}
func Test_LoginRedirectAfterLoginRequired(t *testing.T) {
recorder := httptest.NewRecorder()
m := martini.Classic()
m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
m.Use(Google(&Options{
ClientId: "client_id",
ClientSecret: "client_secret",
RedirectURL: "refresh_url",
Scopes: []string{"x", "y"},
}))
m.Get("/login-required", LoginRequired, func(tokens Tokens) (int, string) {
return 200, tokens.Access()
})
r, _ := http.NewRequest("GET", "/login-required?key=value", nil)
m.ServeHTTP(recorder, r)
location := recorder.HeaderMap["Location"][0]
if recorder.Code != 302 {
t.Errorf("Not being redirected to the auth page.")
}
if location != "/login?next=%2Flogin-required%3Fkey%3Dvalue" {
t.Errorf("Not being redirected to the right page, %v found", location)
}
}
func Test_Logout(t *testing.T) {
recorder := httptest.NewRecorder()
s := sessions.NewCookieStore([]byte("secret123"))
m := martini.Classic()
m.Use(sessions.Sessions("my_session", s))
m.Use(Google(&Options{
// no need to configure
}))
m.Get("/", func(s sessions.Session) {
s.Set(keyToken, "dummy token")
})
m.Get("/get", func(s sessions.Session) {
if s.Get(keyToken) != nil {
t.Errorf("User credentials are still kept in the session.")
}
})
logout, _ := http.NewRequest("GET", "/logout", nil)
index, _ := http.NewRequest("GET", "/", nil)
m.ServeHTTP(httptest.NewRecorder(), index)
m.ServeHTTP(recorder, logout)
if recorder.Code != 302 {
t.Errorf("Not being redirected to the next page.")
}
}
func Test_LogoutOnAccessTokenExpiration(t *testing.T) {
recorder := httptest.NewRecorder()
s := sessions.NewCookieStore([]byte("secret123"))
m := martini.Classic()
m.Use(sessions.Sessions("my_session", s))
m.Use(Google(&Options{
// no need to configure
}))
m.Get("/addtoken", func(s sessions.Session) {
s.Set(keyToken, "dummy token")
})
m.Get("/", func(s sessions.Session) {
if s.Get(keyToken) != nil {
t.Errorf("User not logged out although access token is expired.")
}
})
addtoken, _ := http.NewRequest("GET", "/addtoken", nil)
index, _ := http.NewRequest("GET", "/", nil)
m.ServeHTTP(recorder, addtoken)
m.ServeHTTP(recorder, index)
}
func Test_InjectedTokens(t *testing.T) {
recorder := httptest.NewRecorder()
m := martini.Classic()
m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
m.Use(Google(&Options{
// no need to configure
}))
m.Get("/", func(tokens Tokens) string {
return "Hello world!"
})
r, _ := http.NewRequest("GET", "/", nil)
m.ServeHTTP(recorder, r)
}
func Test_LoginRequired(t *testing.T) {
recorder := httptest.NewRecorder()
m := martini.Classic()
m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
m.Use(Google(&Options{
// no need to configure
}))
m.Get("/", LoginRequired, func(tokens Tokens) string {
return "Hello world!"
})
r, _ := http.NewRequest("GET", "/", nil)
m.ServeHTTP(recorder, r)
if recorder.Code != 302 {
t.Errorf("Not being redirected to the auth page although user is not logged in.")
}
}

View File

@ -1231,3 +1231,77 @@ html, body {
#footer a {
color: #000;
}
/* admin dashboard/configuration */
.admin-dl-horizontal > dt {
width: 220px;
}
.admin-dl-horizontal > dd {
margin-left: 240px;
}
/* release page */
#release-head {
margin-top: 0;
padding-bottom: 30px;
margin-bottom: 0;
border-bottom: 1px solid #DDD;
}
#release .release-item .col-md-10 {
border-left: 1px solid #DDD;
position: relative;
}
#release .release-item .commit, #release .release-item .tag {
display: block;
margin-top: 12px;
}
#release .release-item.release-tag .commit {
margin-top: 6px;
}
#release .release-item .title {
line-height: 30px;
margin-top: 0;
}
#release .release-item .dot {
width: 9px;
height: 9px;
background-color: #ccc;
z-index: 999;
position: absolute;
display: block;
left: -5px;
top: 30px;
border-radius: 6px;
border: 1px solid #FFF;
}
#release .release-item > div {
padding-top: 20px;
padding-bottom: 20px;
}
#release .release-item p.info {
line-height: 20px;
color: #666;
margin-bottom: 18px;
}
#release .release-item div.desc {
margin-bottom: 18px;
}
#release .release-item p.info > *, #release .release-item .download a {
margin-right: 12px;
}
#release .release-item .info .avatar {
vertical-align: middle;
}

BIN
public/js/ZeroClipboard.swf Normal file

Binary file not shown.

View File

@ -159,6 +159,7 @@ var Gogits = {
$tabs.tab("show");
$tabs.find("li:eq(0) a").tab("show");
};
// fix dropdown inside click
Gogits.initDropDown = function () {
$('.dropdown-menu.no-propagation').on('click', function (e) {
@ -166,6 +167,7 @@ var Gogits = {
});
};
// render markdown
Gogits.renderMarkdown = function () {
var $md = $('.markdown');
@ -192,6 +194,7 @@ var Gogits = {
});
};
// render code view
Gogits.renderCodeView = function () {
function selectRange($list, $select, $from) {
$list.removeClass('active');
@ -255,6 +258,43 @@ var Gogits = {
}).trigger('hashchange');
};
// copy utils
Gogits.bindCopy = function (selector) {
if ($(selector).hasClass('js-copy-bind')) {
return;
}
$(selector).zclip({
path: "/js/ZeroClipboard.swf",
copy: function () {
var t = $(this).data("copy-val");
var to = $($(this).data("copy-from"));
var str = "";
if (t == "txt") {
str = to.text();
}
if (t == 'val') {
str = to.val();
}
if (t == 'html') {
str = to.html();
}
return str;
},
afterCopy: function () {
var $this = $(this);
$this.tooltip('hide')
.attr('data-original-title', 'Copied OK');
setTimeout(function () {
$this.tooltip("show");
}, 200);
setTimeout(function () {
$this.tooltip('hide')
.attr('data-original-title', 'Copy to Clipboard');
}, 3000);
}
}).addClass("js-copy-bind");
}
})(jQuery);
// ajax utils
@ -343,7 +383,10 @@ function initRepository() {
$clone.find('span.clone-url').text($this.data('link'));
}
}).eq(0).trigger("click");
// todo copy to clipboard
$("#repo-clone").on("shown.bs.dropdown",function () {
Gogits.bindCopy("[data-init=copy]");
});
Gogits.bindCopy("[data-init=copy]:visible");
}
})();

File diff suppressed because one or more lines are too long

View File

@ -6,6 +6,7 @@ package routers
import (
"errors"
"fmt"
"os"
"strings"
@ -42,7 +43,7 @@ func GlobalInit() {
if base.InstallLock {
if err := models.NewEngine(); err != nil {
log.Error("%v", err)
fmt.Println(err)
os.Exit(2)
}

View File

@ -31,7 +31,8 @@ func Issues(ctx *middleware.Context) {
ctx.Data["IssueCreatedCount"] = 0
var posterId int64 = 0
if ctx.Query("type") == "created_by" {
isCreatedBy := ctx.Query("type") == "created_by"
if isCreatedBy {
if !ctx.IsSigned {
ctx.SetCookie("redirect_to", "/"+url.QueryEscape(ctx.Req.RequestURI))
ctx.Redirect("/user/login/", 302)
@ -53,6 +54,7 @@ func Issues(ctx *middleware.Context) {
}
var createdByCount int
showIssues := make([]models.Issue, 0, len(issues))
// Get posters.
for i := range issues {
u, err := models.GetUserById(issues[i].PosterId)
@ -60,15 +62,19 @@ func Issues(ctx *middleware.Context) {
ctx.Handle(200, "issue.Issues(get poster): %v", err)
return
}
issues[i].Poster = u
if isCreatedBy && u.Id != posterId {
continue
}
if u.Id == posterId {
createdByCount++
}
issues[i].Poster = u
showIssues = append(showIssues, issues[i])
}
ctx.Data["Issues"] = issues
ctx.Data["Issues"] = showIssues
ctx.Data["IssueCount"] = ctx.Repo.Repository.NumIssues
ctx.Data["OpenCount"] = ctx.Repo.Repository.NumIssues - ctx.Repo.Repository.NumClosedIssues
ctx.Data["OpenCount"] = ctx.Repo.Repository.NumOpenIssues
ctx.Data["ClosedCount"] = ctx.Repo.Repository.NumClosedIssues
ctx.Data["IssueCreatedCount"] = createdByCount
ctx.Data["IsShowClosed"] = ctx.Query("state") == "closed"
@ -107,7 +113,7 @@ func CreateIssue(ctx *middleware.Context, params martini.Params, form auth.Creat
// Mail watchers.
if base.Service.NotifyMail {
if err = mailer.SendNotifyMail(ctx.User.Id, ctx.Repo.Repository.Id, ctx.User.Name, ctx.Repo.Repository.Name, issue.Name, issue.Content); err != nil {
if err = mailer.SendNotifyMail(ctx.User, ctx.Repo.Owner, ctx.Repo.Repository, issue); err != nil {
ctx.Handle(200, "issue.CreateIssue", err)
return
}

22
routers/repo/release.go Normal file
View File

@ -0,0 +1,22 @@
// 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 repo
import (
"github.com/gogits/gogs/models"
"github.com/gogits/gogs/modules/middleware"
)
func Releases(ctx *middleware.Context) {
ctx.Data["Title"] = "Releases"
ctx.Data["IsRepoToolbarReleases"] = true
tags, err := models.GetTags(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
if err != nil {
ctx.Handle(404, "repo.Releases(GetTags)", err)
return
}
ctx.Data["Releases"] = tags
ctx.HTML(200, "release/list")
}

View File

@ -5,6 +5,7 @@
package repo
import (
"fmt"
"path"
"path/filepath"
"strings"
@ -245,10 +246,10 @@ func Http(ctx *middleware.Context, params martini.Params) {
reponame = reponame[:len(reponame)-4]
}
dir := models.RepoPath(username, reponame)
prefix := path.Join("/", username, params["reponame"])
server := webdav.NewServer(
models.RepoPath(username, reponame),
prefix, true)
dir, prefix, true)
server.ServeHTTP(ctx.ResponseWriter, ctx.Req)
}
@ -278,19 +279,67 @@ func SettingPost(ctx *middleware.Context) {
switch ctx.Query("action") {
case "update":
isNameChanged := false
newRepoName := ctx.Query("name")
// Check if repository name has been changed.
if ctx.Repo.Repository.Name != newRepoName {
isExist, err := models.IsRepositoryExist(ctx.Repo.Owner, newRepoName)
if err != nil {
ctx.Handle(404, "repo.SettingPost(update: check existence)", err)
return
} else if isExist {
ctx.RenderWithErr("Repository name has been taken in your repositories.", "repo/setting", nil)
return
} else if err = models.ChangeRepositoryName(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name, newRepoName); err != nil {
ctx.Handle(404, "repo.SettingPost(change repository name)", err)
return
}
log.Trace("%s Repository name changed: %s/%s -> %s", ctx.Req.RequestURI, ctx.User.Name, ctx.Repo.Repository.Name, newRepoName)
isNameChanged = true
ctx.Repo.Repository.Name = newRepoName
}
ctx.Repo.Repository.Description = ctx.Query("desc")
ctx.Repo.Repository.Website = ctx.Query("site")
if err := models.UpdateRepository(ctx.Repo.Repository); err != nil {
ctx.Handle(404, "repo.SettingPost(update)", err)
return
}
ctx.Data["IsSuccess"] = true
if isNameChanged {
ctx.Redirect(fmt.Sprintf("/%s/%s/settings", ctx.Repo.Owner.Name, ctx.Repo.Repository.Name))
} else {
ctx.HTML(200, "repo/setting")
log.Trace("%s Repository updated: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.Repo.Repository.LowerName)
}
log.Trace("%s Repository updated: %s/%s", ctx.Req.RequestURI, ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
case "transfer":
if len(ctx.Repo.Repository.Name) == 0 || ctx.Repo.Repository.Name != ctx.Query("repository") {
ctx.RenderWithErr("Please make sure you entered repository name is correct.", "repo/setting", nil)
return
}
newOwner := ctx.Query("owner")
// Check if new owner exists.
isExist, err := models.IsUserExist(newOwner)
if err != nil {
ctx.Handle(404, "repo.SettingPost(transfer: check existence)", err)
return
} else if !isExist {
ctx.RenderWithErr("Please make sure you entered owner name is correct.", "repo/setting", nil)
return
} else if err = models.TransferOwnership(ctx.User, newOwner, ctx.Repo.Repository); err != nil {
ctx.Handle(404, "repo.SettingPost(transfer repository)", err)
return
}
log.Trace("%s Repository transfered: %s/%s -> %s", ctx.Req.RequestURI, ctx.User.Name, ctx.Repo.Repository.Name, newOwner)
ctx.Redirect("/")
return
case "delete":
if len(ctx.Repo.Repository.Name) == 0 || ctx.Repo.Repository.Name != ctx.Query("repository") {
ctx.Data["ErrorMsg"] = "Please make sure you entered repository name is correct."
ctx.HTML(200, "repo/setting")
ctx.RenderWithErr("Please make sure you entered repository name is correct.", "repo/setting", nil)
return
}

View File

@ -23,15 +23,27 @@ func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) {
user := ctx.User
ctx.Data["Owner"] = user
if ctx.Req.Method == "GET" {
if ctx.Req.Method == "GET" || ctx.HasError() {
ctx.HTML(200, "user/setting")
return
}
// below is for POST requests
if hasErr, ok := ctx.Data["HasError"]; ok && hasErr.(bool) {
ctx.HTML(200, "user/setting")
// Check if user name has been changed.
if user.Name != form.UserName {
isExist, err := models.IsUserExist(form.UserName)
if err != nil {
ctx.Handle(404, "user.Setting(update: check existence)", err)
return
} else if isExist {
ctx.RenderWithErr("User name has been taken.", "user/setting", &form)
return
} else if err = models.ChangeUserName(user, form.UserName); err != nil {
ctx.Handle(404, "user.Setting(change user name)", err)
return
}
log.Trace("%s User name changed: %s -> %s", ctx.Req.RequestURI, user.Name, form.UserName)
user.Name = form.UserName
}
user.Email = form.Email
@ -46,7 +58,6 @@ func Setting(ctx *middleware.Context, form auth.UpdateProfileForm) {
ctx.Data["IsSuccess"] = true
ctx.HTML(200, "user/setting")
log.Trace("%s User setting updated: %s", ctx.Req.RequestURI, ctx.User.LowerName)
}

49
routers/user/social.go Normal file
View File

@ -0,0 +1,49 @@
// 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 user
import (
"encoding/json"
"code.google.com/p/goauth2/oauth"
"github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/oauth2"
)
// github && google && ...
func SocialSignIn(tokens oauth2.Tokens) {
transport := &oauth.Transport{}
transport.Token = &oauth.Token{
AccessToken: tokens.Access(),
RefreshToken: tokens.Refresh(),
Expiry: tokens.ExpiryTime(),
Extra: tokens.ExtraData(),
}
// Github API refer: https://developer.github.com/v3/users/
// FIXME: need to judge url
type GithubUser struct {
Id int `json:"id"`
Name string `json:"login"`
Email string `json:"email"`
}
// Make the request.
scope := "https://api.github.com/user"
r, err := transport.Client().Get(scope)
if err != nil {
log.Error("connect with github error: %s", err)
// FIXME: handle error page
return
}
defer r.Body.Close()
user := &GithubUser{}
err = json.NewDecoder(r.Body).Decode(user)
if err != nil {
log.Error("Get: %s", err)
}
log.Info("login: %s", user.Name)
// FIXME: login here, user email to check auth, if not registe, then generate a uniq username
}

View File

@ -2,22 +2,31 @@
{{template "base/navbar" .}}
<div id="body" class="container" data-page="admin">
{{template "admin/nav" .}}
<div id="admin-container" class="col-md-9">
<div id="admin-container" class="col-md-10">
<div class="panel panel-default">
<div class="panel-heading">
Server Configuration
</div>
<div class="panel-body">
<div><b>Application Name:</b> {{AppName}}</div>
<div><b>Application Version:</b> {{AppVer}}</div>
<div><b>Application URL:</b> {{.AppUrl}}</div>
<div><b>Domain:</b> {{.Domain}}</div>
<dl class="dl-horizontal admin-dl-horizontal">
<dt>Application Name</dt>
<dd>{{AppName}}</dd>
<dt>Application Version</dt>
<dd>{{AppVer}}</dd>
<dt>Application URL</dt>
<dd>{{.AppUrl}}</dd>
<dt>Domain</dt>
<dd>{{.Domain}}</dd>
<hr/>
<div><b>Run User:</b> {{.RunUser}}</div>
<div><b>Run Mode:</b> {{.RunMode}}</div>
<dt>Run User</dt>
<dd>{{.RunUser}}</dd>
<dt>Run Mode</dt>
<dd>{{.RunMode}}</dd>
<hr/>
<div><b>Repository Root Path:</b> {{.RepoRootPath}}</div>
<dt>Repository Root Path</dt>
<dd>{{.RepoRootPath}}</dd>
</dl>
</div>
</div>
@ -27,12 +36,20 @@
</div>
<div class="panel-body">
<div><b>Type:</b> {{.DbCfg.Type}}</div>
<div><b>Host:</b> {{.DbCfg.Host}}</div>
<div><b>Name:</b> {{.DbCfg.Name}}</div>
<div><b>User:</b> {{.DbCfg.User}}</div>
<div><b>SslMode:</b> {{.DbCfg.SslMode}} (for "postgres" only)</div>
<div><b>Path:</b> {{.DbCfg.Path}} (for "sqlite3" only)</div>
<dl class="dl-horizontal admin-dl-horizontal">
<dt>Type</dt>
<dd>{{.DbCfg.Type}}</dd>
<dt>Host</dt>
<dd>{{.DbCfg.Host}}</dd>
<dt>Name</dt>
<dd>{{.DbCfg.Name}}</dd>
<dt>User</dt>
<dd>{{.DbCfg.User}}</dd>
<dt>SslMode</dt>
<dd>{{.DbCfg.SslMode}} (for "postgres" only)</dd>
<dt>Path</dt>
<dd>{{.DbCfg.Path}} (for "sqlite3" only)</dd>
</dl>
</div>
</div>
@ -42,14 +59,23 @@
</div>
<div class="panel-body">
<div><b>Register Email Confirmation:</b> <i class="fa fa{{if .Service.RegisterEmailConfirm}}-check{{end}}-square-o"></i></div>
<div><b>Disenable Registeration:</b> <i class="fa fa{{if .Service.DisenableRegisteration}}-check{{end}}-square-o"></i></div>
<div><b>Require Sign In View:</b> <i class="fa fa{{if .Service.RequireSignInView}}-check{{end}}-square-o"></i></div>
<div><b>Mail Notification:</b> <i class="fa fa{{if .Service.NotifyMail}}-check{{end}}-square-o"></i></div>
<div><b>Enable Cache Avatar:</b> <i class="fa fa{{if .Service.EnableCacheAvatar}}-check{{end}}-square-o"></i></div>
<dl class="dl-horizontal admin-dl-horizontal">
<dt>Register Email Confirmation</dt>
<dd><i class="fa fa{{if .Service.RegisterEmailConfirm}}-check{{end}}-square-o"></i></dd>
<dt>Disenable Registeration</dt>
<dd><i class="fa fa{{if .Service.DisenableRegisteration}}-check{{end}}-square-o"></i></dd>
<dt>Require Sign In View</dt>
<dd><i class="fa fa{{if .Service.RequireSignInView}}-check{{end}}-square-o"></i></dd>
<dt>Mail Notification</dt>
<dd><i class="fa fa{{if .Service.NotifyMail}}-check{{end}}-square-o"></i></dd>
<dt>Enable Cache Avatar</dt>
<dd><i class="fa fa{{if .Service.EnableCacheAvatar}}-check{{end}}-square-o"></i></dd>
<hr/>
<div><b>Active Code Lives:</b> {{.Service.ActiveCodeLives}} minutes</div>
<div><b>Reset Password Code Lives:</b> {{.Service.ResetPwdCodeLives}} minutes</div>
<dt>Active Code Lives</dt>
<dd>{{.Service.ActiveCodeLives}} minutes</dd>
<dt>Reset Password Code Lives</dt>
<dd>{{.Service.ResetPwdCodeLives}} minutes</dd>
</dl>
</div>
</div>
@ -59,10 +85,16 @@
</div>
<div class="panel-body">
<div><b>Enabled:</b> <i class="fa fa{{if .MailerEnabled}}-check{{end}}-square-o"></i></div>
<div><b>Name:</b> {{.Mailer.Name}}</div>
<div><b>Host:</b> {{.Mailer.Host}}</div>
<div><b>User:</b> {{.Mailer.User}}</div>
<dl class="dl-horizontal admin-dl-horizontal">
<dt>Enabled</dt>
<dd><i class="fa fa{{if .MailerEnabled}}-check{{end}}-square-o"></i></dd>
<dt>Name</dt>
<dd>{{.Mailer.Name}}</dd>
<dt>Host</dt>
<dd>{{.Mailer.Host}}</dd>
<dt>User</dt>
<dd>{{.Mailer.User}}</dd>
</dl>
</div>
</div>
@ -72,9 +104,12 @@
</div>
<div class="panel-body">
<div><b>Cache Adapter:</b> {{.CacheAdapter}}</div>
<div><b>Cache Config:</b></div>
<div style="padding-top: 5px;"><pre>{{.CacheConfig}}</pre></div>
<dl class="dl-horizontal admin-dl-horizontal">
<dt>Cache Adapter</dt>
<dd>{{.CacheAdapter}}</dd>
<dt>Cache Config</dt>
<dd><div style="padding-top: 5px;"><pre>{{.CacheConfig}}</pre></div></dd>
</dl>
</div>
</div>
@ -84,16 +119,28 @@
</div>
<div class="panel-body">
<div><b>Session Provider:</b> {{.SessionProvider}}</div>
<div><b>Cookie Name:</b> {{.SessionConfig.CookieName}}</div>
<div><b>Enable Set Cookie:</b> <i class="fa fa{{if .SessionConfig.EnableSetCookie}}-check{{end}}-square-o"></i></div>
<div><b>GC Interval Time:</b> {{.SessionConfig.GcIntervalTime}} seconds</div>
<div><b>Session Life Time:</b> {{.SessionConfig.SessionLifeTime}} seconds</div>
<div><b>HTTPS Only:</b> <i class="fa fa{{if .SessionConfig.CookieSecure}}-check{{end}}-square-o"></i></div>
<div><b>Cookie Life Time:</b> {{.SessionConfig.CookieLifeTime}} seconds</div>
<div><b>Session ID Hash Function:</b> {{.SessionConfig.SessionIDHashFunc}}</div>
<div><b>Session ID Hash Key:</b> {{.SessionConfig.SessionIDHashKey}}</div>
<div><b>Provider Config:</b> {{.SessionConfig.ProviderConfig}}</div>
<dl class="dl-horizontal admin-dl-horizontal">
<dt>Session Provider</dt>
<dd>{{.SessionProvider}}</dd>
<dt>Cookie Name</dt>
<dd>{{.SessionConfig.CookieName}}</dd>
<dt>Enable Set Cookie</dt>
<dd><i class="fa fa{{if .SessionConfig.EnableSetCookie}}-check{{end}}-square-o"></i></dd>
<dt>GC Interval Time</dt>
<dd>{{.SessionConfig.GcIntervalTime}} seconds</dd>
<dt>Session Life Time</dt>
<dd>{{.SessionConfig.SessionLifeTime}} seconds</dd>
<dt>HTTPS Only</dt>
<dd><i class="fa fa{{if .SessionConfig.CookieSecure}}-check{{end}}-square-o"></i></dd>
<dt>Cookie Life Time</dt>
<dd>{{.SessionConfig.CookieLifeTime}} seconds</dd>
<dt>Session ID Hash Function</dt>
<dd>{{.SessionConfig.SessionIDHashFunc}}</dd>
<dt>Session ID Hash Key</dt>
<dd>{{.SessionConfig.SessionIDHashKey}}</dd>
<dt>Provider Config</dt>
<dd>{{.SessionConfig.ProviderConfig}}</dd>
</dl>
</div>
</div>
@ -103,7 +150,10 @@
</div>
<div class="panel-body">
<div><b>Picture Service:</b> {{.PictureService}}</div>
<dl class="dl-horizontal admin-dl-horizontal">
<dt>Picture Service</dt>
<dd>{{.PictureService}}</dd>
</dl>
</div>
</div>
@ -113,9 +163,14 @@
</div>
<div class="panel-body">
<div><b>Log Mode:</b> {{.LogMode}}</div>
<div><b>Log Config:</b></div>
<dl class="dl-horizontal admin-dl-horizontal">
<dt>Log Mode</dt>
<dd>{{.LogMode}}</dd>
<dt>Log Config</dt>
<dd>
<div style="padding-top: 5px;"><pre>{{.LogConfig}}</pre></div>
</dd>
</dl>
</div>
</div>

View File

@ -2,7 +2,7 @@
{{template "base/navbar" .}}
<div id="body" class="container" data-page="admin">
{{template "admin/nav" .}}
<div id="admin-container" class="col-md-9">
<div id="admin-container" class="col-md-10">
<div class="panel panel-default">
<div class="panel-heading">
Statistic
@ -19,38 +19,95 @@
</div>
<div class="panel-body">
<div>Server Uptime: <b>{{.SysStatus.Uptime}}</b></div>
<div>Current Goroutines: <b>{{.SysStatus.NumGoroutine}}</b></div>
<dl class="dl-horizontal admin-dl-horizontal">
<dt>Server Uptime</dt>
<dd>{{.SysStatus.Uptime}}</dd>
<dt>Current Goroutines</dt>
<dd>{{.SysStatus.NumGoroutine}}</dd>
<hr/>
<div>Current Memory Usage: <b>{{.SysStatus.MemAllocated}}</b></div>
<div>Total Memory Allocated: <b>{{.SysStatus.MemTotal}}</b></div>
<div>Memory Obtained: <b>{{.SysStatus.MemSys}}</b></div>
<div>Pointer Lookup Times: <b>{{.SysStatus.Lookups}}</b></div>
<div>Memory Allocate Times: <b>{{.SysStatus.MemMallocs}}</b></div>
<div>Memory Free Times: <b>{{.SysStatus.MemFrees}}</b></div>
<dt>Current Memory Usage</dt>
<dd>{{.SysStatus.MemAllocated}}</dd>
<dt>Total Memory Allocated</dt>
<dd>{{.SysStatus.MemTotal}}</dd>
<dt>Memory Obtained</dt>
<dd>{{.SysStatus.MemSys}}</dd>
<dt>Pointer Lookup Times</dt>
<dd>{{.SysStatus.Lookups}}</dd>
<dt>Memory Allocate Times</dt>
<dd>{{.SysStatus.MemMallocs}}</dd>
<dt>Memory Free Times</dt>
<dd>{{.SysStatus.MemFrees}}</dd>
<hr/>
<div>Current Heap Usage: <b>{{.SysStatus.HeapAlloc}}</b></div>
<div>Heap Memory Obtained: <b>{{.SysStatus.HeapSys}}</b></div>
<div>Heap Memory Idle: <b>{{.SysStatus.HeapIdle}}</b></div>
<div>Heap Memory In Use: <b>{{.SysStatus.HeapInuse}}</b></div>
<div>Heap Memory Released: <b>{{.SysStatus.HeapReleased}}</b></div>
<div>Heap Objects: <b>{{.SysStatus.HeapObjects}}</b></div>
<dt>Current Heap Usage</dt>
<dd>{{.SysStatus.HeapAlloc}}</dd>
<dt>Heap Memory Obtained</dt>
<dd>{{.SysStatus.HeapSys}}</dd>
<dt>Heap Memory Idle</dt>
<dd>{{.SysStatus.HeapIdle}}</dd>
<dt>Heap Memory In Use</dt>
<dd>{{.SysStatus.HeapInuse}}</dd>
<dt>Heap Memory Released</dt>
<dd>{{.SysStatus.HeapReleased}}</dd>
<dt>Heap Objects</dt>
<dd>{{.SysStatus.HeapObjects}}</dd>
<hr/>
<div>Bootstrap Stack Usage: <b>{{.SysStatus.StackInuse}}</b></div>
<div>Stack Memory Obtained: <b>{{.SysStatus.StackSys}}</b></div>
<div>MSpan Structures Usage: <b>{{.SysStatus.MSpanInuse}}</b></div>
<div>MSpan Structures Obtained: <b>{{.SysStatus.HeapSys}}</b></div>
<div>MCache Structures Usage: <b>{{.SysStatus.MCacheInuse}}</b></div>
<div>MCache Structures Obtained: <b>{{.SysStatus.MCacheSys}}</b></div>
<div>Profiling Bucket Hash Table Obtained: <b>{{.SysStatus.BuckHashSys}}</b></div>
<div>GC Metadada Obtained: <b>{{.SysStatus.GCSys}}</b></div>
<div>Other System Allocation Obtained: <b>{{.SysStatus.OtherSys}}</b></div>
<dt>Bootstrap Stack Usage</dt>
<dd>{{.SysStatus.StackInuse}}</dd>
<dt>Stack Memory Obtained</dt>
<dd>{{.SysStatus.StackSys}}</dd>
<dt>MSpan Structures Usage</dt>
<dd>{{.SysStatus.MSpanInuse}}</dd>
<dt>MSpan Structures Obtained</dt>
<dd>{{.SysStatus.HeapSys}}</dd>
<dt>MCache Structures Usage</dt>
<dd>{{.SysStatus.MCacheInuse}}</dd>
<dt>MCache Structures Obtained</dt>
<dd>{{.SysStatus.MCacheSys}}</dd>
<dt>Profiling Bucket Hash Table Obtained</dt>
<dd>{{.SysStatus.BuckHashSys}}</dd>
<dt>GC Metadada Obtained</dt>
<dd>{{.SysStatus.GCSys}}</dd>
<dt>Other System Allocation Obtained</dt>
<dd>{{.SysStatus.OtherSys}}</dd>
<hr/>
<div>Next GC Recycle: <b>{{.SysStatus.NextGC}}</b></div>
<div>Last GC Time: <b>{{.SysStatus.LastGC}} ago</b></div>
<div>Total GC Pause: <b>{{.SysStatus.PauseTotalNs}}</b></div>
<div>Last GC Pause: <b>{{.SysStatus.PauseNs}}</b></div>
<div>GC Times: <b>{{.SysStatus.NumGC}}</b></div>
<dt>Next GC Recycle</dt>
<dd>{{.SysStatus.NextGC}}</dd>
<dt>Last GC Time</dt>
<dd>{{.SysStatus.LastGC}} ago</dd>
<dt>Total GC Pause</dt>
<dd>{{.SysStatus.PauseTotalNs}}</dd>
<dt>Last GC Pause</dt>
<dd>{{.SysStatus.PauseNs}}</dd>
<dt>GC Times</dt>
<dd>{{.SysStatus.NumGC}}</dd>
</dl>
</div>
</div>
</div>

View File

@ -1,4 +1,4 @@
<div id="user-setting-nav" class="col-md-3 admin-nav">
<div id="user-setting-nav" class="col-md-2 admin-nav">
<ul class="list-group">
<li class="list-group-item{{if .PageIsDashboard}} active{{end}}"><a href="/admin"><i class="fa fa-tachometer fa-lg"></i> Dashboard</a></li>
<li class="list-group-item{{if .PageIsUsers}} active{{end}}"><a href="/admin/users"><i class="fa fa-users fa-lg"></i> Users</a></li>

View File

@ -2,7 +2,7 @@
{{template "base/navbar" .}}
<div id="body" class="container" data-page="admin">
{{template "admin/nav" .}}
<div id="admin-container" class="col-md-9">
<div id="admin-container" class="col-md-10">
<div class="panel panel-default">
<div class="panel-heading">
Repository Management

View File

@ -2,7 +2,7 @@
{{template "base/navbar" .}}
<div id="body" class="container" data-page="admin">
{{template "admin/nav" .}}
<div id="admin-container" class="col-md-9">
<div id="admin-container" class="col-md-10">
<div class="panel panel-default">
<div class="panel-heading">
User Management

View File

@ -0,0 +1,86 @@
{{template "base/head" .}}
{{template "base/navbar" .}}
{{template "repo/nav" .}}
{{template "repo/toolbar" .}}
<div id="body" class="container">
<div id="release">
<h4 id="release-head">
<span class="release"><strong>Release</strong></span> /
<a class="tag" href="/{tag_link}">Tags</a>
<!-- comment : if in tag page, show a.release and span.tag please -->
</h4>
<ul id="release-list" class="list-unstyled">
<li class="release-item release-tag clearfix" id="release-tag-{release_tag_id}">
<div class="col-md-2 text-right">
<a class="commit" href="{commit_link}"><i class="fa fa-code"></i>commit-sha</a>
</div>
<div class="col-md-10">
<h5 class="title"><a href="{release_single_link}">Release Tag</a><i class="fa fa-tag"></i></h5>
<p class="info">
<span class="author"><img class="avatar" src="http://1.gravatar.com/avatar/f72f7454ce9d710baa506394f68f4132" alt="" width="20">&nbsp;&nbsp;
<a href="/user/fuxiaohei">fuxiaohei</a></span>
<span class="time">1 week ago</span>
<span class="ahead"><strong>0</strong> commits since this tag</span>
</p>
<p class="download">
<a class="download-link" href="{release_download_link}"><i class="fa fa-download"></i>zip</a>
<a class="download-link" href="{release_download_link}"><i class="fa fa-download"></i>tar.gz</a>
</p>
<span class="dot">&nbsp;</span>
</div>
</li>
<li class="release-item clearfix" id="release-{release_id}">
<div class="col-md-2 text-right">
<span class="btn btn-success status stable">Stable</span>
<a class="tag" href="{commit_link}"><i class="fa fa-tag"></i>release tag</a>
<a class="commit" href="{commit_link}"><i class="fa fa-code"></i>commit-sha</a>
</div>
<div class="col-md-10">
<h4 class="title"><a href="{release_single_link}">Release Title</a></h4>
<p class="info">
<span class="author"><img class="avatar" src="http://1.gravatar.com/avatar/f72f7454ce9d710baa506394f68f4132" alt="" width="20">&nbsp;&nbsp;
<a href="/user/fuxiaohei">fuxiaohei</a></span>
<span class="time">1 week ago</span>
<span class="ahead"><strong>0</strong> commits since this tag</span>
</p>
<div class="markdown desc">
release descriptions, support markdown content
</div>
<p class="download">
<a class="btn btn-default" href="{release_download_link}"><i class="fa fa-download"></i>Source Code (ZIP)</a>
<a class="btn btn-default" href="{release_download_link}"><i class="fa fa-download"></i>Source Code (TAR.GZ)</a>
</p>
<span class="dot">&nbsp;</span>
</div>
</li>
<li class="release-item clearfix" id="release-{release_id}">
<div class="col-md-2 text-right">
<span class="btn btn-warning status pre-release">Pre-Release</span>
<a class="tag" href="{commit_link}"><i class="fa fa-tag"></i>release tag</a>
<a class="commit" href="{commit_link}"><i class="fa fa-code"></i>commit-sha</a>
</div>
<div class="col-md-10">
<h4 class="title"><a href="{release_single_link}">Release Title</a></h4>
<p class="info">
<span class="author"><img class="avatar" src="http://1.gravatar.com/avatar/f72f7454ce9d710baa506394f68f4132" alt="" width="20">&nbsp;&nbsp;
<a href="/user/fuxiaohei">fuxiaohei</a></span>
<span class="time">1 week ago</span>
<span class="ahead"><strong>0</strong> commits since this tag</span>
</p>
<div class="markdown desc">
release descriptions, support markdown content
</div>
<p class="download">
<a class="btn btn-default" href="{release_download_link}"><i class="fa fa-download"></i>Source Code (ZIP)</a>
<a class="btn btn-default" href="{release_download_link}"><i class="fa fa-download"></i>Source Code (TAR.GZ)</a>
</p>
<span class="dot">&nbsp;</span>
</div>
</li>
</ul>
</div>
{{range .Releases}}
{{.}}
{{end}}
</div>
{{template "base/footer" .}}

View File

@ -18,9 +18,9 @@
<button class="btn btn-default" data-link="{{.CloneLink.SSH}}" type="button">SSH</button>
<button class="btn btn-default" data-link="{{.CloneLink.HTTPS}}" type="button">HTTPS</button>
</span>
<input type="text" class="form-control clone-group-url" value="" readonly/>
<input type="text" class="form-control clone-group-url" value="" readonly id="repo-clone-ipt"/>
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-copy" data-toggle="tooltip" title="copy to clipboard" data-placement="top"></i></button>
<button class="btn btn-default" type="button" data-toggle="tooltip" title="copy to clipboard" data-placement="top" data-init="copy" data-copy-val="val" data-copy-from="#repo-clone-ipt"><i class="fa fa-copy"></i></button>
</span>
</div>
<p class="help-block text-center">Need help cloning? Visit <a href="#">Help</a>!</p>

View File

@ -12,7 +12,7 @@
</div>
<div id="repo-setting-container" class="col-md-9">
{{if .IsSuccess}}<p class="alert alert-success">Repository option has been successfully updated.</p>{{else if .HasError}}<p class="alert alert-danger form-error">{{.ErrorMsg}}</p>{{end}}
{{if .IsSuccess}}<p class="alert alert-success">Repository options has been successfully updated.</p>{{else if .HasError}}<p class="alert alert-danger form-error">{{.ErrorMsg}}</p>{{end}}
<div class="panel panel-default">
<div class="panel-heading">
Repository Options
@ -22,12 +22,20 @@
<form action="/{{.Owner.Name}}/{{.Repository.Name}}/settings" method="post" class="form-horizontal">
{{.CsrfTokenHtml}}
<input type="hidden" name="action" value="update">
<div class="form-group">
<label class="col-md-3 text-right">Name</label>
<div class="col-md-9">
<input class="form-control" name="name" value="{{.Repository.Name}}" title="{{.Repository.Name}}" />
</div>
</div>
<div class="form-group">
<label class="col-md-3 text-right">Description</label>
<div class="col-md-9">
<textarea class="form-control" name="desc" id="repo-desc" rows="3">{{.Repository.Description}}</textarea>
</div>
</div>
<div class="form-group">
<label class="col-md-3 text-right">Official Site</label>
<div class="col-md-9">
@ -56,12 +64,62 @@
Danger Zone
</div>
<div class="panel-body">
<button type="button" class="btn btn-default pull-right" href="#transfer-repository-modal" data-toggle="modal">
Transfer ownership
</button>
<dd>
<dt>Transfer ownership</dt>
<dl>Transfer this repo to another user or to an organization where you have admin rights.</dl>
</dd>
<div class="modal fade" id="transfer-repository-modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<form action="/{{.Owner.Name}}/{{.Repository.Name}}/settings" method="post" class="modal-content">
{{.CsrfTokenHtml}}
<input type="hidden" name="action" value="transfer">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 class="modal-title" id="myModalLabel">Do you really want to transfer this repo?</h4>
</div>
<div class="modal-body">
<div class="alert alert-warning">This is important, pay attention.</div>
<ul>
<!-- <li>Transferring may be delayed until the new owner approves the transfer.</li> -->
<!-- <li>If you are transferring into an org, teams <strong>will not be set</strong>. An owner on the org will need to set teams for the repo.</li> -->
<li>Admin rights will be transferred to the new owner, you <strong>will lose admin rights</strong>.</li>
<!-- <li>Admin rights will be transferred to the new owner, you <strong>may lose admin rights</strong> if you are transferring into an organization account.</li> -->
<li>Redirect entries <strong>will NOT be</strong> set up from the previous location.</li>
<li>Git access <strong>will NOT continue</strong> to work from the previous location.</li>
</ul>
<div class="form-group">
<label>Please type the name of the repository to confirm "<strong class="text-danger">{{.Repository.Name}}</strong>"</label>
<input name="repository" class="form-control" type="text" placeholder="Type your repository name" required="required">
</div>
<div class="form-group">
<label>Please type the name of the new owner:</label>
<input name="owner" class="form-control" type="text" placeholder="Type new owner's name" required="required">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button class="btn btn-danger btn-lg">I understand the consequences, transfer this repository</button>
</div>
</form>
</div>
</div>
</div>
<hr>
<div class="panel-body">
<button type="button" class="btn btn-default pull-right" href="#delete-repository-modal" data-toggle="modal">
Delete this repository
</button>
<dd>
<dt>Delete this repository.</dt>
<dt>Delete this repository</dt>
<dl>Once you delete a repository, there is no going back. Please be certain.</dl>
</dd>

View File

@ -17,7 +17,7 @@
</span>
<input type="text" class="form-control clone-group-url" id="guide-clone-url" value="" readonly/>
<span class="input-group-btn">
<button class="btn btn-default" type="button"><i class="fa fa-copy" data-toggle="tooltip" title="copy to clipboard" data-placement="top"></i></button>
<button class="btn btn-default" type="button" data-toggle="tooltip" title="copy to clipboard" data-placement="top" data-init="copy" data-copy-val="val" data-copy-from="#guide-clone-url"><i class="fa fa-copy"></i></button>
</span>
</div>
<p>We recommend every repository include a <strong>README</strong>, <strong>LICENSE</strong>, and <strong>.gitignore</strong>.</p>

View File

@ -8,18 +8,18 @@
<li class="{{if .IsRepoToolbarCommits}}active{{end}}"><a href="{{.RepoLink}}/commits/{{if .BranchName}}{{.BranchName}}{{else}}master{{end}}">Commits</a></li>
<!-- <li class="{{if .IsRepoToolbarBranches}}active{{end}}"><a href="{{.RepoLink}}/branches">Branches</a></li> -->
<!-- <li class="{{if .IsRepoToolbarPulls}}active{{end}}"><a href="{{.RepoLink}}/pulls">Pull Requests</a></li> -->
<li class="{{if .IsRepoToolbarIssues}}active{{end}}"><a href="{{.RepoLink}}/issues">Issues <!--<span class="badge">42</span>--></a></li>
<li class="{{if .IsRepoToolbarIssues}}active{{end}}"><a href="{{.RepoLink}}/issues">{{if .Repository.NumOpenIssues}}<span class="badge">{{.Repository.NumOpenIssues}}</span> {{end}}Issues <!--<span class="badge">42</span>--></a></li>
{{if .IsRepoToolbarIssues}}
<li class="tmp">{{if .IsRepoToolbarIssuesList}}<a href="{{.RepoLink}}/issues/new">
<button class="btn btn-primary btn-sm">New Issue</button>
</a>{{else}}<a href="{{.RepoLink}}/issues">
<button class="btn btn-primary btn-sm">Issues List</button>
</a>{{end}}</li>
<li class="tmp">{{if .IsRepoToolbarIssuesList}}<a href="{{.RepoLink}}/issues/new"><button class="btn btn-primary btn-sm">New Issue</button>
</a>{{else}}<a href="{{.RepoLink}}/issues"><button class="btn btn-primary btn-sm">Issues List</button></a>{{end}}</li>
{{end}}
<li class="{{if .IsRepoToolbarReleases}}active{{end}}"><a href="{{.RepoLink}}/releases">{{if .Repository.NumReleases}}<span class="badge">{{.Repository.NumReleases}}</span> {{end}}Releases</a></li>
{{if .IsRepoToolbarReleases}}
<li class="tmp"><a href="{{.RepoLink}}/releases/new"><button class="btn btn-primary btn-sm">New Release</button></a></li>
{{end}}
<!-- <li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">More <b class="caret"></b></a>
<ul class="dropdown-menu">
<li><a href="{{.RepoLink}}/release">Release</a></li>
<li><a href="{{.RepoLink}}/wiki">Wiki</a></li>
</ul>
</li> -->{{end}}

View File

@ -10,30 +10,37 @@
{{if .IsSuccess}}<p class="alert alert-success">Your profile has been successfully updated.</p>{{else if .HasError}}<p class="alert alert-danger form-error">{{.ErrorMsg}}</p>{{end}}
<p>Your Email will be public and used for Account related notifications and any web based operations made via the web.</p>
<div class="form-group">
<label class="col-md-2 control-label">Email</label>
<label class="col-md-2 control-label">Username<strong class="text-danger">*</strong></label>
<div class="col-md-8">
<input type="text" name="email" class="form-control" placeholder="Type your e-mail address" value="{{.Owner.Email}}">
<input name="username" class="form-control" placeholder="Type your user name" required="required" value="{{.SignedUser.Name}}" title="{{.SignedUser.Name}}">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Email<strong class="text-danger">*</strong></label>
<div class="col-md-8">
<input name="email" class="form-control" placeholder="Type your e-mail address" required="required" value="{{.SignedUser.Email}}">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Website</label>
<div class="col-md-8">
<input type="text" name="website" class="form-control" placeholder="Type your website URL" value="{{.Owner.Website}}">
<input name="website" class="form-control" placeholder="Type your website URL" value="{{.SignedUser.Website}}">
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">Location</label>
<div class="col-md-8">
<input type="text" name="location" class="form-control" placeholder="Type your current location" value="{{.Owner.Location}}">
<input name="location" class="form-control" placeholder="Type your current location" value="{{.SignedUser.Location}}">
</div>
</div>
<div class="form-group {{if .Err_Avatar}}has-error has-feedback{{end}}">
<label class="col-md-2 control-label">Gravatar Email<strong class="text-danger">*</strong></label>
<div class="col-md-8">
<input type="text" name="avatar" class="form-control" placeholder="Type your Gravatar e-mail address" required="required" value="{{.Owner.AvatarEmail}}">
<input name="avatar" class="form-control" placeholder="Type your Gravatar e-mail address" required="required" value="{{.SignedUser.AvatarEmail}}">
</div>
</div>

14
web.go
View File

@ -11,6 +11,8 @@ import (
"github.com/codegangsta/cli"
"github.com/go-martini/martini"
// "github.com/martini-contrib/oauth2"
// "github.com/martini-contrib/sessions"
"github.com/gogits/binding"
@ -58,6 +60,16 @@ func runWeb(*cli.Context) {
// Middlewares.
m.Use(middleware.Renderer(middleware.RenderOptions{Funcs: []template.FuncMap{base.TemplateFuncs}}))
// scope := "https://api.github.com/user"
// oauth2.PathCallback = "/oauth2callback"
// m.Use(sessions.Sessions("my_session", sessions.NewCookieStore([]byte("secret123"))))
// m.Use(oauth2.Github(&oauth2.Options{
// ClientId: "09383403ff2dc16daaa1",
// ClientSecret: "5f6e7101d30b77952aab22b75eadae17551ea6b5",
// RedirectURL: base.AppUrl + oauth2.PathCallback,
// Scopes: []string{scope},
// }))
m.Use(middleware.InitContext())
reqSignIn := middleware.Toggle(&middleware.ToggleOptions{SignInRequire: true})
@ -80,6 +92,7 @@ func runWeb(*cli.Context) {
m.Get("/avatar/:hash", avt.ServeHTTP)
m.Group("/user", func(r martini.Router) {
// r.Any("/login/github", user.SocialSignIn)
r.Any("/login", binding.BindIgnErr(auth.LogInForm{}), user.SignIn)
r.Any("/sign_up", binding.BindIgnErr(auth.RegisterForm{}), user.SignUp)
}, reqSignOut)
@ -134,6 +147,7 @@ func runWeb(*cli.Context) {
m.Group("/:username/:reponame", func(r martini.Router) {
r.Get("/issues", repo.Issues)
r.Get("/issues/:index", repo.ViewIssue)
r.Get("/releases", repo.Releases)
r.Get("/pulls", repo.Pulls)
r.Get("/branches", repo.Branches)
}, ignSignIn, middleware.RepoAssignment(true))