From 5180506678c9c4e7265eaee557d91992ec97fa3a Mon Sep 17 00:00:00 2001 From: skyblue Date: Wed, 2 Apr 2014 10:39:04 +0800 Subject: [PATCH 01/10] split into social.go --- routers/user/social.go | 49 ++++++++++++++++++++++++++++++++++++++++++ routers/user/user.go | 40 ---------------------------------- 2 files changed, 49 insertions(+), 40 deletions(-) create mode 100644 routers/user/social.go diff --git a/routers/user/social.go b/routers/user/social.go new file mode 100644 index 000000000..2f711d58c --- /dev/null +++ b/routers/user/social.go @@ -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/martini-contrib/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 +} diff --git a/routers/user/user.go b/routers/user/user.go index 5890983ba..08930e22d 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -5,14 +5,11 @@ package user import ( - "encoding/json" "fmt" "net/url" "strings" - "code.google.com/p/goauth2/oauth" "github.com/go-martini/martini" - "github.com/martini-contrib/oauth2" "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" @@ -77,43 +74,6 @@ func Profile(ctx *middleware.Context, params martini.Params) { ctx.HTML(200, "user/profile") } -// 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 -} - func SignIn(ctx *middleware.Context, form auth.LogInForm) { ctx.Data["Title"] = "Log In" From 93f6e98047559b188acf8a11468b9c913217b234 Mon Sep 17 00:00:00 2001 From: skyblue Date: Wed, 2 Apr 2014 22:23:45 +0800 Subject: [PATCH 02/10] change oauth2 path --- routers/user/social.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routers/user/social.go b/routers/user/social.go index 2f711d58c..b5c5436ba 100644 --- a/routers/user/social.go +++ b/routers/user/social.go @@ -8,7 +8,7 @@ import ( "code.google.com/p/goauth2/oauth" "github.com/gogits/gogs/modules/log" - "github.com/martini-contrib/oauth2" + "github.com/gogits/oauth2" ) // github && google && ... From adf42a5b547e8e738b8b7e795a0863bc1eab58a5 Mon Sep 17 00:00:00 2001 From: skyblue Date: Wed, 2 Apr 2014 22:27:54 +0800 Subject: [PATCH 03/10] change oauth2 to modules --- modules/oauth2/oauth2.go | 233 ++++++++++++++++++++++++++++++++++ modules/oauth2/oauth2_test.go | 162 +++++++++++++++++++++++ routers/user/social.go | 2 +- 3 files changed, 396 insertions(+), 1 deletion(-) create mode 100644 modules/oauth2/oauth2.go create mode 100644 modules/oauth2/oauth2_test.go diff --git a/modules/oauth2/oauth2.go b/modules/oauth2/oauth2.go new file mode 100644 index 000000000..088d65dda --- /dev/null +++ b/modules/oauth2/oauth2.go @@ -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 +} diff --git a/modules/oauth2/oauth2_test.go b/modules/oauth2/oauth2_test.go new file mode 100644 index 000000000..71443030a --- /dev/null +++ b/modules/oauth2/oauth2_test.go @@ -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.") + } +} diff --git a/routers/user/social.go b/routers/user/social.go index b5c5436ba..b59f49630 100644 --- a/routers/user/social.go +++ b/routers/user/social.go @@ -8,7 +8,7 @@ import ( "code.google.com/p/goauth2/oauth" "github.com/gogits/gogs/modules/log" - "github.com/gogits/oauth2" + "github.com/gogits/gogs/modules/oauth2" ) // github && google && ... From d9005ee970270bca97e81d59edca4722752d160d Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 2 Apr 2014 10:38:30 -0400 Subject: [PATCH 04/10] Improve issue mail content --- gogs.go | 2 +- models/repo.go | 1 + modules/mailer/mail.go | 11 ++++--- public/css/gogs.css | 4 +-- routers/repo/issue.go | 14 ++++++--- routers/user/user.go | 70 +++++++++++++++++++++--------------------- web.go | 24 +++++++-------- 7 files changed, 68 insertions(+), 58 deletions(-) diff --git a/gogs.go b/gogs.go index a81f3ab59..88f53eeb8 100644 --- a/gogs.go +++ b/gogs.go @@ -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.0401 Alpha" +const APP_VER = "0.2.0.0402 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/repo.go b/models/repo.go index 0c808f184..8dd7da23f 100644 --- a/models/repo.go +++ b/models/repo.go @@ -513,6 +513,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()) diff --git a/modules/mailer/mail.go b/modules/mailer/mail.go index d0decbe06..b99fc8fdf 100644 --- a/modules/mailer/mail.go +++ b/modules/mailer/mail.go @@ -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
-
View it on Gogs.", + 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 diff --git a/public/css/gogs.css b/public/css/gogs.css index a018a9dba..6bed77114 100755 --- a/public/css/gogs.css +++ b/public/css/gogs.css @@ -1235,9 +1235,9 @@ html, body { /* admin dashboard/configuration */ .admin-dl-horizontal > dt { - width: 320px; + width: 220px; } .admin-dl-horizontal > dd { - margin-left: 340px; + margin-left: 240px; } diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 6cad2c25d..41b2c7e9b 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -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,13 +62,17 @@ 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["ClosedCount"] = ctx.Repo.Repository.NumClosedIssues @@ -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 } diff --git a/routers/user/user.go b/routers/user/user.go index 5890983ba..c008a05cf 100644 --- a/routers/user/user.go +++ b/routers/user/user.go @@ -5,14 +5,14 @@ package user import ( - "encoding/json" + // "encoding/json" "fmt" "net/url" "strings" - "code.google.com/p/goauth2/oauth" + // "code.google.com/p/goauth2/oauth" "github.com/go-martini/martini" - "github.com/martini-contrib/oauth2" + // "github.com/martini-contrib/oauth2" "github.com/gogits/gogs/models" "github.com/gogits/gogs/modules/auth" @@ -78,41 +78,41 @@ func Profile(ctx *middleware.Context, params martini.Params) { } // 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(), - } +// 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"` - } +// // 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() +// // 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 -} +// 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 +// } func SignIn(ctx *middleware.Context, form auth.LogInForm) { ctx.Data["Title"] = "Log In" diff --git a/web.go b/web.go index 48d80b4fe..ececd6c2b 100644 --- a/web.go +++ b/web.go @@ -11,8 +11,8 @@ import ( "github.com/codegangsta/cli" "github.com/go-martini/martini" - "github.com/martini-contrib/oauth2" - "github.com/martini-contrib/sessions" + // "github.com/martini-contrib/oauth2" + // "github.com/martini-contrib/sessions" "github.com/gogits/binding" @@ -60,15 +60,15 @@ 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}, - })) + // 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()) @@ -92,7 +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/github", user.SocialSignIn) r.Any("/login", binding.BindIgnErr(auth.LogInForm{}), user.SignIn) r.Any("/sign_up", binding.BindIgnErr(auth.RegisterForm{}), user.SignUp) }, reqSignOut) From db66b8da7227f7fd3ff9a8d7ccece0c3e31ea3d0 Mon Sep 17 00:00:00 2001 From: Unknown Date: Wed, 2 Apr 2014 12:43:31 -0400 Subject: [PATCH 05/10] Add release tmpl --- models/git.go | 19 +++++++++++++++++++ models/repo.go | 1 + modules/middleware/repo.go | 1 + routers/repo/issue.go | 2 +- routers/repo/release.go | 22 ++++++++++++++++++++++ templates/release/list.tmpl | 10 ++++++++++ templates/repo/toolbar.tmpl | 11 ++++------- web.go | 1 + 8 files changed, 59 insertions(+), 8 deletions(-) create mode 100644 routers/repo/release.go create mode 100644 templates/release/list.tmpl diff --git a/models/git.go b/models/git.go index d3bad6e0c..46345d0ff 100644 --- a/models/git.go +++ b/models/git.go @@ -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 { diff --git a/models/repo.go b/models/repo.go index 8dd7da23f..e3270b183 100644 --- a/models/repo.go +++ b/models/repo.go @@ -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 diff --git a/modules/middleware/repo.go b/modules/middleware/repo.go index f446d6a85..2139742c7 100644 --- a/modules/middleware/repo.go +++ b/modules/middleware/repo.go @@ -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 diff --git a/routers/repo/issue.go b/routers/repo/issue.go index 41b2c7e9b..be9254264 100644 --- a/routers/repo/issue.go +++ b/routers/repo/issue.go @@ -74,7 +74,7 @@ func Issues(ctx *middleware.Context) { 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" diff --git a/routers/repo/release.go b/routers/repo/release.go new file mode 100644 index 000000000..8e8b93c9e --- /dev/null +++ b/routers/repo/release.go @@ -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") +} diff --git a/templates/release/list.tmpl b/templates/release/list.tmpl new file mode 100644 index 000000000..7d582e3ff --- /dev/null +++ b/templates/release/list.tmpl @@ -0,0 +1,10 @@ +{{template "base/head" .}} +{{template "base/navbar" .}} +{{template "repo/nav" .}} +{{template "repo/toolbar" .}} +
+ {{range .Releases}} + {{.}} + {{end}} +
+{{template "base/footer" .}} \ No newline at end of file diff --git a/templates/repo/toolbar.tmpl b/templates/repo/toolbar.tmpl index 6b48ecf50..08167ef82 100644 --- a/templates/repo/toolbar.tmpl +++ b/templates/repo/toolbar.tmpl @@ -8,18 +8,15 @@
  • Commits
  • -
  • Issues
  • +
  • {{if .Repository.NumOpenIssues}}{{.Repository.NumOpenIssues}} {{end}}Issues
  • {{if .IsRepoToolbarIssues}} -
  • {{if .IsRepoToolbarIssuesList}} - - {{else}} - - {{end}}
  • +
  • {{if .IsRepoToolbarIssuesList}} + {{else}}{{end}}
  • {{end}} +
  • {{if .Repository.NumReleases}}{{.Repository.NumReleases}} {{end}}Releases
  • {{end}} diff --git a/web.go b/web.go index ececd6c2b..5fc3350f1 100644 --- a/web.go +++ b/web.go @@ -147,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)) From 1757a59a999be2c1b3a17244231cad6a579282d4 Mon Sep 17 00:00:00 2001 From: FuXiaoHei Date: Thu, 3 Apr 2014 00:56:26 +0800 Subject: [PATCH 06/10] js clipboard --- public/js/ZeroClipboard.swf | Bin 0 -> 1071 bytes public/js/app.js | 45 +++++++++++++++++++++++++++++++- public/js/lib.js | 13 +++++++++ templates/repo/nav.tmpl | 4 +-- templates/repo/single_bare.tmpl | 2 +- 5 files changed, 60 insertions(+), 4 deletions(-) create mode 100644 public/js/ZeroClipboard.swf diff --git a/public/js/ZeroClipboard.swf b/public/js/ZeroClipboard.swf new file mode 100644 index 0000000000000000000000000000000000000000..13bf8e396202964e0048333d878f4b949a2f5e6a GIT binary patch literal 1071 zcmV+~1kn3KS5pay1^@tfoPAa6Qrkup-d$aeB-A-xFjKf1te)pFM-&Q&_dOT zp~-XxqP4X~YJ}vGWC;KAD1C=MKwiO_PG6^Vbs@z~r#qgr-}!Xr?4IxJ9P1kT4dpSa zmlT9hja*+}e;Cbih*6`(JT|+I(1(#NIVSiTL~Dq=|Lb=d5tOYL`L;_#dyQQ%FAAmI zcth~a_gzLk@xphk!Y?fFYp&C2`ZTZ#X}INt9hY9ojZWZ1Om23g$oC2%i(XLAs&#|V z5ArS7X}yhomj%SJGT~|rnZj|zM|I&j59e1QKqGxQN5!(ijWrx1S)ZN!RwWBwC`$uYc z!)028S7F4?l?H2dd39HKImh$+mv#S~I-YjmQ;P-rUfUM~-;Xr+ldpAXK+hS!b|@Ro zUs)@fv!kf9RjpFXZ?d(Pe_q{bY*sgP{Ykaib==7Da_N!X$Z^AwK5e&BZ5R56j>T=;_5DD$nR8}GiWShym;5A&x*eM;)Us-}<67Eb+@9n>sdlhm z`(coON!$a6H-ML=9U8}t-8aV1yD!xY9v@|7-FWq*lEUMka&b=Hq$X{>72}4eNl_P+ zccPJWGtXb!r#GbVPIO$}sN%oME%Yf<`b@|2f6G5y#$}-l zAR|D=L6`ti0Wt|N4P*v{Ss-&j?gE(yvY_TMkQE@SK-Pd%f#~WwXExMLZXW@84CD#m zFMxar!IU~i}ZGSTvX;GX_!`A@yKkIbSu*e=l_b9m*BF@hOB8SS;p?XkU4 z+#Y{FagI+_hF#pQ*y^c#B7H9*TQ=n-IvJZOQ*KYMV&e{u!2((~XOiIAy*Zr0yBr$x zqA6D~T{u}ZWn+;Cn@jC`refSD34E}PZ{YGaxq%P2g&VlCEyl30qM2Z<#-M2CQxMno zG_4J8H7mc8(VenQzJ;=@j=BiTh*RubMeS$61ORcM^S6!u6l;=?s|@ py1A~K8@jovn~!u;;=k8uI$3rc`gC{*rT-s&a~N%N=5J58nk1s|4c7nw literal 0 HcmV?d00001 diff --git a/public/js/app.js b/public/js/app.js index 5181933d2..0ba0675f2 100644 --- a/public/js/app.js +++ b/public/js/app.js @@ -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"); } })(); diff --git a/public/js/lib.js b/public/js/lib.js index 8735ac9c1..bd42152b0 100644 --- a/public/js/lib.js +++ b/public/js/lib.js @@ -480,3 +480,16 @@ PR.registerLangHandler(PR.createSimpleLexer([["kwd",/^#[a-z]+/i,null,"#"]],[]),[ var a=null; var a=null; PR.registerLangHandler(PR.createSimpleLexer([["pun",/^[:>?|]+/,a,":|>?"],["dec",/^%(?:YAML|TAG)[^\n\r#]+/,a,"%"],["typ",/^&\S+/,a,"&"],["typ",/^!\S*/,a,"!"],["str",/^"(?:[^"\\]|\\.)*(?:"|$)/,a,'"'],["str",/^'(?:[^']|'')*(?:'|$)/,a,"'"],["com",/^#[^\n\r]*/,a,"#"],["pln",/^\s+/,a," \t\r\n"]],[["dec",/^(?:---|\.\.\.)(?:[\n\r]|$)/],["pun",/^-/],["kwd",/^\w+:[\n\r ]/],["pln",/^\w+/]]),["yaml","yml"]); + +/* + * zClip :: jQuery ZeroClipboard v1.1.1 + * http://steamdev.com/zclip + * + * Copyright 2011, SteamDev + * Released under the MIT license. + * http://www.opensource.org/licenses/mit-license.php + * + * Date: Wed Jun 01, 2011 + */ + +(function(a){a.fn.zclip=function(c){if(typeof c=="object"&&!c.length){var b=a.extend({path:"ZeroClipboard.swf",copy:null,beforeCopy:null,afterCopy:null,clickAfter:true,setHandCursor:true,setCSSEffects:true},c);return this.each(function(){var e=a(this);if(e.is(":visible")&&(typeof b.copy=="string"||a.isFunction(b.copy))){ZeroClipboard.setMoviePath(b.path);var d=new ZeroClipboard.Client();if(a.isFunction(b.copy)){e.bind("zClip_copy",b.copy)}if(a.isFunction(b.beforeCopy)){e.bind("zClip_beforeCopy",b.beforeCopy)}if(a.isFunction(b.afterCopy)){e.bind("zClip_afterCopy",b.afterCopy)}d.setHandCursor(b.setHandCursor);d.setCSSEffects(b.setCSSEffects);d.addEventListener("mouseOver",function(f){e.trigger("mouseenter")});d.addEventListener("mouseOut",function(f){e.trigger("mouseleave")});d.addEventListener("mouseDown",function(f){e.trigger("mousedown");if(!a.isFunction(b.copy)){d.setText(b.copy)}else{d.setText(e.triggerHandler("zClip_copy"))}if(a.isFunction(b.beforeCopy)){e.trigger("zClip_beforeCopy")}});d.addEventListener("complete",function(f,g){if(a.isFunction(b.afterCopy)){e.trigger("zClip_afterCopy")}else{if(g.length>500){g=g.substr(0,500)+"...\n\n("+(g.length-500)+" characters not shown)"}e.removeClass("hover");alert("Copied text to clipboard:\n\n "+g)}if(b.clickAfter){e.trigger("click")}});d.glue(e[0],e.parent()[0]);a(window).bind("load resize",function(){d.reposition()})}})}else{if(typeof c=="string"){return this.each(function(){var f=a(this);c=c.toLowerCase();var e=f.data("zclipId");var d=a("#"+e+".zclip");if(c=="remove"){d.remove();f.removeClass("active hover")}else{if(c=="hide"){d.hide();f.removeClass("active hover")}else{if(c=="show"){d.show()}}}})}}}})(jQuery);var ZeroClipboard={version:"1.0.7",clients:{},moviePath:"ZeroClipboard.swf",nextId:1,$:function(a){if(typeof(a)=="string"){a=document.getElementById(a)}if(!a.addClass){a.hide=function(){/*this.style.display="none"*/};a.show=function(){this.style.display=""};a.addClass=function(b){this.removeClass(b);this.className+=" "+b};a.removeClass=function(d){var e=this.className.split(/\s+/);var b=-1;for(var c=0;c-1){e.splice(b,1);this.className=e.join(" ")}return this};a.hasClass=function(b){return !!this.className.match(new RegExp("\\s*"+b+"\\s*"))}}return a},setMoviePath:function(a){this.moviePath=a},dispatch:function(d,b,c){var a=this.clients[d];if(a){a.receiveEvent(b,c)}},register:function(b,a){this.clients[b]=a},getDOMObjectPosition:function(c,a){var b={left:0,top:0,width:c.width?c.width:c.offsetWidth,height:c.height?c.height:c.offsetHeight};if(c&&(c!=a)){b.left+=c.offsetLeft;b.top+=c.offsetTop}return b},Client:function(a){this.handlers={};this.id=ZeroClipboard.nextId++;this.movieId="ZeroClipboardMovie_"+this.id;ZeroClipboard.register(this.id,this);if(a){this.glue(a)}}};ZeroClipboard.Client.prototype={id:0,ready:false,movie:null,clipText:"",handCursorEnabled:true,cssEffects:true,handlers:null,glue:function(d,b,e){this.domElement=ZeroClipboard.$(d);var f=99;if(this.domElement.style.zIndex){f=parseInt(this.domElement.style.zIndex,10)+1}if(typeof(b)=="string"){b=ZeroClipboard.$(b)}else{if(typeof(b)=="undefined"){b=document.getElementsByTagName("body")[0]}}var c=ZeroClipboard.getDOMObjectPosition(this.domElement,b);this.div=document.createElement("div");this.div.className="zclip";this.div.id="zclip-"+this.movieId;$(this.domElement).data("zclipId","zclip-"+this.movieId);var a=this.div.style;a.position="absolute";a.left=""+c.left+"px";a.top=""+c.top+"px";a.width=""+c.width+"px";a.height=""+c.height+"px";a.zIndex=f;if(typeof(e)=="object"){for(addedStyle in e){a[addedStyle]=e[addedStyle]}}b.appendChild(this.div);this.div.innerHTML=this.getHTML(c.width,c.height)},getHTML:function(d,a){var c="";var b="id="+this.id+"&width="+d+"&height="+a;if(navigator.userAgent.match(/MSIE/)){var e=location.href.match(/^https/i)?"https://":"http://";c+=''}else{c+=''}return c},hide:function(){if(this.div){this.div.style.left="-2000px"}},show:function(){this.reposition()},destroy:function(){if(this.domElement&&this.div){this.hide();this.div.innerHTML="";var a=document.getElementsByTagName("body")[0];try{a.removeChild(this.div)}catch(b){}this.domElement=null;this.div=null}},reposition:function(c){if(c){this.domElement=ZeroClipboard.$(c);if(!this.domElement){this.hide()}}if(this.domElement&&this.div){var b=ZeroClipboard.getDOMObjectPosition(this.domElement);var a=this.div.style;a.left=""+b.left+"px";a.top=""+b.top+"px"}},setText:function(a){this.clipText=a;if(this.ready){this.movie.setText(a)}},addEventListener:function(a,b){a=a.toString().toLowerCase().replace(/^on/,"");if(!this.handlers[a]){this.handlers[a]=[]}this.handlers[a].push(b)},setHandCursor:function(a){this.handCursorEnabled=a;if(this.ready){this.movie.setHandCursor(a)}},setCSSEffects:function(a){this.cssEffects=!!a},receiveEvent:function(d,f){d=d.toString().toLowerCase().replace(/^on/,"");switch(d){case"load":this.movie=document.getElementById(this.movieId);if(!this.movie){var c=this;setTimeout(function(){c.receiveEvent("load",null)},1);return}if(!this.ready&&navigator.userAgent.match(/Firefox/)&&navigator.userAgent.match(/Windows/)){var c=this;setTimeout(function(){c.receiveEvent("load",null)},100);this.ready=true;return}this.ready=true;try{this.movie.setText(this.clipText)}catch(h){}try{this.movie.setHandCursor(this.handCursorEnabled)}catch(h){}break;case"mouseover":if(this.domElement&&this.cssEffects){this.domElement.addClass("hover");if(this.recoverActive){this.domElement.addClass("active")}}break;case"mouseout":if(this.domElement&&this.cssEffects){this.recoverActive=false;if(this.domElement.hasClass("active")){this.domElement.removeClass("active");this.recoverActive=true}this.domElement.removeClass("hover")}break;case"mousedown":if(this.domElement&&this.cssEffects){this.domElement.addClass("active")}break;case"mouseup":if(this.domElement&&this.cssEffects){this.domElement.removeClass("active");this.recoverActive=false}break}if(this.handlers[d]){for(var b=0,a=this.handlers[d].length;bSSH - + - +

    Need help cloning? Visit Help!

    diff --git a/templates/repo/single_bare.tmpl b/templates/repo/single_bare.tmpl index 035e78e8b..fc0a3bd96 100644 --- a/templates/repo/single_bare.tmpl +++ b/templates/repo/single_bare.tmpl @@ -17,7 +17,7 @@ - +

    We recommend every repository include a README, LICENSE, and .gitignore.

    From bfdadaa13c5dc289beed8e13c6e0d8a0eabeae37 Mon Sep 17 00:00:00 2001 From: skyblue Date: Thu, 3 Apr 2014 11:13:35 +0800 Subject: [PATCH 07/10] add oauth2 models --- models/oauth2.go | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 models/oauth2.go diff --git a/models/oauth2.go b/models/oauth2.go new file mode 100644 index 000000000..70dcd5100 --- /dev/null +++ b/models/oauth2.go @@ -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"` +} From 79a610592ea7c2e93ab2f91190af1782c4aa8f8d Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 3 Apr 2014 15:50:55 -0400 Subject: [PATCH 08/10] Add: rename repository --- models/access.go | 8 ++++++++ models/repo.go | 22 +++++++++++++++++++++- modules/middleware/context.go | 4 +++- routers/repo/repo.go | 34 ++++++++++++++++++++++++++++++---- templates/repo/setting.tmpl | 10 +++++++++- 5 files changed, 71 insertions(+), 7 deletions(-) diff --git a/models/access.go b/models/access.go index 42fccae05..83261575e 100644 --- a/models/access.go +++ b/models/access.go @@ -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{ diff --git a/models/repo.go b/models/repo.go index e3270b183..11e23ecd0 100644 --- a/models/repo.go +++ b/models/repo.go @@ -369,14 +369,34 @@ func RepoPath(userName, repoName string) string { return filepath.Join(UserPath(userName), strings.ToLower(repoName)+".git") } +// 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, 5) + err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}) + if 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 } diff --git a/modules/middleware/context.go b/modules/middleware/context.go index d2b268cd8..8129b13b7 100644 --- a/modules/middleware/context.go +++ b/modules/middleware/context.go @@ -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 - auth.AssignForm(form, ctx.Data) + if form != nil { + auth.AssignForm(form, ctx.Data) + } ctx.HTML(200, tpl) } diff --git a/routers/repo/repo.go b/routers/repo/repo.go index 1cd3dd86b..a55647a31 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -5,6 +5,7 @@ package repo import ( + "fmt" "path" "path/filepath" "strings" @@ -278,19 +279,44 @@ 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(update)", 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 - ctx.HTML(200, "repo/setting") - log.Trace("%s Repository updated: %s/%s", ctx.Req.RequestURI, ctx.User.LowerName, ctx.Repo.Repository.LowerName) + 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.Repo.Owner.Name, ctx.Repo.Repository.Name) 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 } diff --git a/templates/repo/setting.tmpl b/templates/repo/setting.tmpl index ea7a5ddb6..a177aba6a 100644 --- a/templates/repo/setting.tmpl +++ b/templates/repo/setting.tmpl @@ -12,7 +12,7 @@
    - {{if .IsSuccess}}

    Repository option has been successfully updated.

    {{else if .HasError}}

    {{.ErrorMsg}}

    {{end}} + {{if .IsSuccess}}

    Repository options has been successfully updated.

    {{else if .HasError}}

    {{.ErrorMsg}}

    {{end}}
    Repository Options @@ -22,12 +22,20 @@
    {{.CsrfTokenHtml}} +
    + +
    + +
    +
    +
    +
    From e9c4156c874ceeecc81fdf7fe00ff2f582110ecd Mon Sep 17 00:00:00 2001 From: Unknown Date: Thu, 3 Apr 2014 16:33:27 -0400 Subject: [PATCH 09/10] Add: rename user --- gogs.go | 2 +- models/repo.go | 5 ++-- models/user.go | 49 +++++++++++++++++++++++++++++++++++++ modules/auth/user.go | 2 ++ routers/repo/repo.go | 2 +- routers/user/setting.go | 23 ++++++++++++----- templates/user/setting.tmpl | 17 +++++++++---- 7 files changed, 84 insertions(+), 16 deletions(-) diff --git a/gogs.go b/gogs.go index 88f53eeb8..034e131bc 100644 --- a/gogs.go +++ b/gogs.go @@ -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.0402 Alpha" +const APP_VER = "0.2.0.0403 Alpha" func init() { base.AppVer = APP_VER diff --git a/models/repo.go b/models/repo.go index 11e23ecd0..56f289097 100644 --- a/models/repo.go +++ b/models/repo.go @@ -372,9 +372,8 @@ func RepoPath(userName, repoName string) string { // 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, 5) - err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}) - if err != nil { + accesses := make([]Access, 0, 10) + if err = orm.Find(&accesses, &Access{RepoName: strings.ToLower(userName + "/" + oldRepoName)}); err != nil { return err } for i := range accesses { diff --git a/models/user.go b/models/user.go index 4908552f2..c5e46b480 100644 --- a/models/user.go +++ b/models/user.go @@ -203,8 +203,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 +277,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 { diff --git a/modules/auth/user.go b/modules/auth/user.go index 2d3c29fde..015059f7d 100644 --- a/modules/auth/user.go +++ b/modules/auth/user.go @@ -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", diff --git a/routers/repo/repo.go b/routers/repo/repo.go index a55647a31..ae51c5513 100644 --- a/routers/repo/repo.go +++ b/routers/repo/repo.go @@ -291,7 +291,7 @@ func SettingPost(ctx *middleware.Context) { 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(update)", err) + 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) diff --git a/routers/user/setting.go b/routers/user/setting.go index 75adf2b81..4b6d88a36 100644 --- a/routers/user/setting.go +++ b/routers/user/setting.go @@ -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") - return + // 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) } diff --git a/templates/user/setting.tmpl b/templates/user/setting.tmpl index 283a8df8b..f44218cde 100644 --- a/templates/user/setting.tmpl +++ b/templates/user/setting.tmpl @@ -10,30 +10,37 @@ {{if .IsSuccess}}

    Your profile has been successfully updated.

    {{else if .HasError}}

    {{.ErrorMsg}}

    {{end}}

    Your Email will be public and used for Account related notifications and any web based operations made via the web.

    - +
    - + +
    +
    + +
    + +
    +
    - +
    - +
    - +
    From 75db79b4b6bcb8f61dd957c9bd21b32d4746f866 Mon Sep 17 00:00:00 2001 From: FuXiaoHei Date: Fri, 4 Apr 2014 20:54:00 +0800 Subject: [PATCH 10/10] release list page ui --- public/css/gogs.css | 72 +++++++++++++++++++++++++++++++++-- templates/release/list.tmpl | 76 +++++++++++++++++++++++++++++++++++++ templates/repo/toolbar.tmpl | 3 ++ 3 files changed, 147 insertions(+), 4 deletions(-) diff --git a/public/css/gogs.css b/public/css/gogs.css index 6bed77114..a6d6b4cce 100755 --- a/public/css/gogs.css +++ b/public/css/gogs.css @@ -1166,7 +1166,7 @@ html, body { font-weight: normal; } -#issue .issue-child .panel-heading .user,#issue .issue-closed a.user,#issue .issue-opened a.user { +#issue .issue-child .panel-heading .user, #issue .issue-closed a.user, #issue .issue-opened a.user { font-weight: bold; } @@ -1174,7 +1174,7 @@ html, body { border-color: #CCC; } -#issue .issue-is-closed .issue-line{ +#issue .issue-is-closed .issue-line { display: none; } @@ -1193,7 +1193,7 @@ html, body { width: 60%; } -#issue .issue-closed .issue-content,#issue .issue-opened .issue-content{ +#issue .issue-closed .issue-content, #issue .issue-opened .issue-content { line-height: 42px; } @@ -1203,7 +1203,7 @@ html, body { padding-bottom: 24px; } -#issue .issue-closed .label-danger,#issue .issue-opened .label-success{ +#issue .issue-closed .label-danger, #issue .issue-opened .label-success { margin: 0 .8em; } @@ -1241,3 +1241,67 @@ html, body { .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; +} \ No newline at end of file diff --git a/templates/release/list.tmpl b/templates/release/list.tmpl index 7d582e3ff..d7c4674e8 100644 --- a/templates/release/list.tmpl +++ b/templates/release/list.tmpl @@ -3,6 +3,82 @@ {{template "repo/nav" .}} {{template "repo/toolbar" .}}
    +
    +

    + Release / + Tags + +

    + +
    {{range .Releases}} {{.}} {{end}} diff --git a/templates/repo/toolbar.tmpl b/templates/repo/toolbar.tmpl index 08167ef82..548420483 100644 --- a/templates/repo/toolbar.tmpl +++ b/templates/repo/toolbar.tmpl @@ -14,6 +14,9 @@ {{else}}{{end}} {{end}}
  • {{if .Repository.NumReleases}}{{.Repository.NumReleases}} {{end}}Releases
  • + {{if .IsRepoToolbarReleases}} +
  • + {{end}}