diff --git a/.travis.yml b/.travis.yml index 1e58d6b..fddc71c 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,9 +1,9 @@ language: go go: - - "1.11.x" + - "1.13.x" env: - GO111MODULE=on script: make ci diff --git a/account.go b/account.go index 6fb8053..2dcfd27 100644 --- a/account.go +++ b/account.go @@ -1,1104 +1,1108 @@ /* * Copyright © 2018-2019 A Bunch Tell LLC. * * This file is part of WriteFreely. * * WriteFreely is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, included * in the LICENSE file in this source code package. */ package writefreely import ( "encoding/json" "fmt" "html/template" "net/http" "regexp" "strings" "sync" "time" "github.com/gorilla/mux" "github.com/gorilla/sessions" "github.com/guregu/null/zero" "github.com/writeas/impart" "github.com/writeas/web-core/auth" "github.com/writeas/web-core/data" "github.com/writeas/web-core/log" "github.com/writeas/writefreely/author" "github.com/writeas/writefreely/config" "github.com/writeas/writefreely/page" ) type ( userSettings struct { Username string `schema:"username" json:"username"` Email string `schema:"email" json:"email"` NewPass string `schema:"new-pass" json:"new_pass"` OldPass string `schema:"current-pass" json:"current_pass"` IsLogOut bool `schema:"logout" json:"logout"` } UserPage struct { page.StaticPage PageTitle string Separator template.HTML IsAdmin bool CanInvite bool } ) func NewUserPage(app *App, r *http.Request, u *User, title string, flashes []string) *UserPage { up := &UserPage{ StaticPage: pageForReq(app, r), PageTitle: title, } up.Username = u.Username up.Flashes = flashes up.Path = r.URL.Path up.IsAdmin = u.IsAdmin() up.CanInvite = canUserInvite(app.cfg, up.IsAdmin) return up } func canUserInvite(cfg *config.Config, isAdmin bool) bool { return cfg.App.UserInvites != "" && (isAdmin || cfg.App.UserInvites != "admin") } func (up *UserPage) SetMessaging(u *User) { //up.NeedsAuth = app.db.DoesUserNeedAuth(u.ID) } const ( loginAttemptExpiration = 3 * time.Second ) var actuallyUsernameReg = regexp.MustCompile("username is actually ([a-z0-9\\-]+)\\. Please try that, instead") func apiSignup(app *App, w http.ResponseWriter, r *http.Request) error { _, err := signup(app, w, r) return err } func signup(app *App, w http.ResponseWriter, r *http.Request) (*AuthUser, error) { reqJSON := IsJSON(r) // Get params var ur userRegistration if reqJSON { decoder := json.NewDecoder(r.Body) err := decoder.Decode(&ur) if err != nil { log.Error("Couldn't parse signup JSON request: %v\n", err) return nil, ErrBadJSON } } else { // Check if user is already logged in u := getUserSession(app, r) if u != nil { return &AuthUser{User: u}, nil } err := r.ParseForm() if err != nil { log.Error("Couldn't parse signup form request: %v\n", err) return nil, ErrBadFormData } err = app.formDecoder.Decode(&ur, r.PostForm) if err != nil { log.Error("Couldn't decode signup form request: %v\n", err) return nil, ErrBadFormData } } return signupWithRegistration(app, ur, w, r) } func signupWithRegistration(app *App, signup userRegistration, w http.ResponseWriter, r *http.Request) (*AuthUser, error) { reqJSON := IsJSON(r) // Validate required params (alias) if signup.Alias == "" { return nil, impart.HTTPError{http.StatusBadRequest, "A username is required."} } if signup.Pass == "" { return nil, impart.HTTPError{http.StatusBadRequest, "A password is required."} } var desiredUsername string if signup.Normalize { // With this option we simply conform the username to what we expect // without complaining. Since they might've done something funny, like // enter: write.as/Way Out There, we'll use their raw input for the new // collection name and sanitize for the slug / username. desiredUsername = signup.Alias signup.Alias = getSlug(signup.Alias, "") } if !author.IsValidUsername(app.cfg, signup.Alias) { // Ensure the username is syntactically correct. return nil, impart.HTTPError{http.StatusPreconditionFailed, "Username is reserved or isn't valid. It must be at least 3 characters long, and can only include letters, numbers, and hyphens."} } // Handle empty optional params // TODO: remove this var createdWithPass := true hashedPass, err := auth.HashPass([]byte(signup.Pass)) if err != nil { return nil, impart.HTTPError{http.StatusInternalServerError, "Could not create password hash."} } // Create struct to insert u := &User{ Username: signup.Alias, HashedPass: hashedPass, HasPass: createdWithPass, Email: prepareUserEmail(signup.Email, app.keys.EmailKey), Created: time.Now().Truncate(time.Second).UTC(), } // Create actual user if err := app.db.CreateUser(app.cfg, u, desiredUsername); err != nil { return nil, err } // Log invite if needed if signup.InviteCode != "" { cu, err := app.db.GetUserForAuth(signup.Alias) if err != nil { return nil, err } err = app.db.CreateInvitedUser(signup.InviteCode, cu.ID) if err != nil { return nil, err } } // Add back unencrypted data for response if signup.Email != "" { u.Email.String = signup.Email } resUser := &AuthUser{ User: u, } if !createdWithPass { resUser.Password = signup.Pass } title := signup.Alias if signup.Normalize { title = desiredUsername } resUser.Collections = &[]Collection{ { Alias: signup.Alias, Title: title, }, } var token string if reqJSON && !signup.Web { token, err = app.db.GetAccessToken(u.ID) if err != nil { return nil, impart.HTTPError{http.StatusInternalServerError, "Could not create access token. Try re-authenticating."} } resUser.AccessToken = token } else { session, err := app.sessionStore.Get(r, cookieName) if err != nil { // The cookie should still save, even if there's an error. // Source: https://github.com/gorilla/sessions/issues/16#issuecomment-143642144 log.Error("Session: %v; ignoring", err) } session.Values[cookieUserVal] = resUser.User.Cookie() err = session.Save(r, w) if err != nil { log.Error("Couldn't save session: %v", err) return nil, err } } if reqJSON { return resUser, impart.WriteSuccess(w, resUser, http.StatusCreated) } return resUser, nil } func viewLogout(app *App, w http.ResponseWriter, r *http.Request) error { session, err := app.sessionStore.Get(r, cookieName) if err != nil { return ErrInternalCookieSession } // Ensure user has an email or password set before they go, so they don't // lose access to their account. val := session.Values[cookieUserVal] var u = &User{} var ok bool if u, ok = val.(*User); !ok { log.Error("Error casting user object on logout. Vals: %+v Resetting cookie.", session.Values) err = session.Save(r, w) if err != nil { log.Error("Couldn't save session on logout: %v", err) return impart.HTTPError{http.StatusInternalServerError, "Unable to save cookie session."} } return impart.HTTPError{http.StatusFound, "/"} } u, err = app.db.GetUserByID(u.ID) if err != nil && err != ErrUserNotFound { return impart.HTTPError{http.StatusInternalServerError, "Unable to fetch user information."} } session.Options.MaxAge = -1 err = session.Save(r, w) if err != nil { log.Error("Couldn't save session on logout: %v", err) return impart.HTTPError{http.StatusInternalServerError, "Unable to save cookie session."} } return impart.HTTPError{http.StatusFound, "/"} } func handleAPILogout(app *App, w http.ResponseWriter, r *http.Request) error { accessToken := r.Header.Get("Authorization") if accessToken == "" { return ErrNoAccessToken } t := auth.GetToken(accessToken) if len(t) == 0 { return ErrNoAccessToken } err := app.db.DeleteToken(t) if err != nil { return err } return impart.HTTPError{Status: http.StatusNoContent} } func viewLogin(app *App, w http.ResponseWriter, r *http.Request) error { var earlyError string oneTimeToken := r.FormValue("with") if oneTimeToken != "" { log.Info("Calling login with one-time token.") err := login(app, w, r) if err != nil { log.Info("Received error: %v", err) earlyError = fmt.Sprintf("%s", err) } } session, err := app.sessionStore.Get(r, cookieName) if err != nil { // Ignore this log.Error("Unable to get session; ignoring: %v", err) } p := &struct { page.StaticPage To string Message template.HTML Flashes []template.HTML LoginUsername string + OauthSlack bool + OauthWriteAs bool }{ pageForReq(app, r), r.FormValue("to"), template.HTML(""), []template.HTML{}, getTempInfo(app, "login-user", r, w), + app.Config().SlackOauth.ClientID != "", + app.Config().WriteAsOauth.ClientID != "", } if earlyError != "" { p.Flashes = append(p.Flashes, template.HTML(earlyError)) } // Display any error messages flashes, _ := getSessionFlashes(app, w, r, session) for _, flash := range flashes { p.Flashes = append(p.Flashes, template.HTML(flash)) } err = pages["login.tmpl"].ExecuteTemplate(w, "base", p) if err != nil { log.Error("Unable to render login: %v", err) return err } return nil } func webLogin(app *App, w http.ResponseWriter, r *http.Request) error { err := login(app, w, r) if err != nil { username := r.FormValue("alias") // Login request was unsuccessful; save the error in the session and redirect them if err, ok := err.(impart.HTTPError); ok { session, _ := app.sessionStore.Get(r, cookieName) if session != nil { session.AddFlash(err.Message) session.Save(r, w) } if m := actuallyUsernameReg.FindStringSubmatch(err.Message); len(m) > 0 { // Retain fixed username recommendation for the login form username = m[1] } } // Pass along certain information saveTempInfo(app, "login-user", username, r, w) // Retain post-login URL if one was given redirectTo := "/login" postLoginRedirect := r.FormValue("to") if postLoginRedirect != "" { redirectTo += "?to=" + postLoginRedirect } log.Error("Unable to login: %v", err) return impart.HTTPError{http.StatusTemporaryRedirect, redirectTo} } return nil } var loginAttemptUsers = sync.Map{} func login(app *App, w http.ResponseWriter, r *http.Request) error { reqJSON := IsJSON(r) oneTimeToken := r.FormValue("with") verbose := r.FormValue("all") == "true" || r.FormValue("verbose") == "1" || r.FormValue("verbose") == "true" || (reqJSON && oneTimeToken != "") redirectTo := r.FormValue("to") if redirectTo == "" { if app.cfg.App.SingleUser { redirectTo = "/me/new" } else { redirectTo = "/" } } var u *User var err error var signin userCredentials // Log in with one-time token if one is given if oneTimeToken != "" { log.Info("Login: Logging user in via token.") userID := app.db.GetUserID(oneTimeToken) if userID == -1 { log.Error("Login: Got user -1 from token") err := ErrBadAccessToken err.Message = "Expired or invalid login code." return err } log.Info("Login: Found user %d.", userID) u, err = app.db.GetUserByID(userID) if err != nil { log.Error("Unable to fetch user on one-time token login: %v", err) return impart.HTTPError{http.StatusInternalServerError, "There was an error retrieving the user you want."} } log.Info("Login: Got user via token") } else { // Get params if reqJSON { decoder := json.NewDecoder(r.Body) err := decoder.Decode(&signin) if err != nil { log.Error("Couldn't parse signin JSON request: %v\n", err) return ErrBadJSON } } else { err := r.ParseForm() if err != nil { log.Error("Couldn't parse signin form request: %v\n", err) return ErrBadFormData } err = app.formDecoder.Decode(&signin, r.PostForm) if err != nil { log.Error("Couldn't decode signin form request: %v\n", err) return ErrBadFormData } } log.Info("Login: Attempting login for '%s'", signin.Alias) // Validate required params (all) if signin.Alias == "" { msg := "Parameter `alias` required." if signin.Web { msg = "A username is required." } return impart.HTTPError{http.StatusBadRequest, msg} } if !signin.EmailLogin && signin.Pass == "" { msg := "Parameter `pass` required." if signin.Web { msg = "A password is required." } return impart.HTTPError{http.StatusBadRequest, msg} } // Prevent excessive login attempts on the same account // Skip this check in dev environment if !app.cfg.Server.Dev { now := time.Now() attemptExp, att := loginAttemptUsers.LoadOrStore(signin.Alias, now.Add(loginAttemptExpiration)) if att { if attemptExpTime, ok := attemptExp.(time.Time); ok { if attemptExpTime.After(now) { // This user attempted previously, and the period hasn't expired yet return impart.HTTPError{http.StatusTooManyRequests, "You're doing that too much."} } else { // This user attempted previously, but the time expired; free up space loginAttemptUsers.Delete(signin.Alias) } } else { log.Error("Unable to cast expiration to time") } } } // Retrieve password u, err = app.db.GetUserForAuth(signin.Alias) if err != nil { log.Info("Unable to getUserForAuth on %s: %v", signin.Alias, err) if strings.IndexAny(signin.Alias, "@") > 0 { log.Info("Suggesting: %s", ErrUserNotFoundEmail.Message) return ErrUserNotFoundEmail } return err } // Authenticate if u.Email.String == "" { // User has no email set, so check if they haven't added a password, either, // so we can return a more helpful error message. if hasPass, _ := app.db.IsUserPassSet(u.ID); !hasPass { log.Info("Tried logging in to %s, but no password or email.", signin.Alias) return impart.HTTPError{http.StatusPreconditionFailed, "This user never added a password or email address. Please contact us for help."} } } if !auth.Authenticated(u.HashedPass, []byte(signin.Pass)) { return impart.HTTPError{http.StatusUnauthorized, "Incorrect password."} } } if reqJSON && !signin.Web { var token string if r.Header.Get("User-Agent") == "" { // Get last created token when User-Agent is empty token = app.db.FetchLastAccessToken(u.ID) if token == "" { token, err = app.db.GetAccessToken(u.ID) } } else { token, err = app.db.GetAccessToken(u.ID) } if err != nil { log.Error("Login: Unable to create access token: %v", err) return impart.HTTPError{http.StatusInternalServerError, "Could not create access token. Try re-authenticating."} } resUser := getVerboseAuthUser(app, token, u, verbose) return impart.WriteSuccess(w, resUser, http.StatusOK) } session, err := app.sessionStore.Get(r, cookieName) if err != nil { // The cookie should still save, even if there's an error. log.Error("Login: Session: %v; ignoring", err) } // Remove unwanted data session.Values[cookieUserVal] = u.Cookie() err = session.Save(r, w) if err != nil { log.Error("Login: Couldn't save session: %v", err) // TODO: return error } // Send success if reqJSON { return impart.WriteSuccess(w, &AuthUser{User: u}, http.StatusOK) } log.Info("Login: Redirecting to %s", redirectTo) w.Header().Set("Location", redirectTo) w.WriteHeader(http.StatusFound) return nil } func getVerboseAuthUser(app *App, token string, u *User, verbose bool) *AuthUser { resUser := &AuthUser{ AccessToken: token, User: u, } // Fetch verbose user data if requested if verbose { posts, err := app.db.GetUserPosts(u) if err != nil { log.Error("Login: Unable to get user posts: %v", err) } colls, err := app.db.GetCollections(u, app.cfg.App.Host) if err != nil { log.Error("Login: Unable to get user collections: %v", err) } passIsSet, err := app.db.IsUserPassSet(u.ID) if err != nil { // TODO: correct error meesage log.Error("Login: Unable to get user collections: %v", err) } resUser.Posts = posts resUser.Collections = colls resUser.User.HasPass = passIsSet } return resUser } func viewExportOptions(app *App, u *User, w http.ResponseWriter, r *http.Request) error { // Fetch extra user data p := NewUserPage(app, r, u, "Export", nil) showUserPage(w, "export", p) return nil } func viewExportPosts(app *App, w http.ResponseWriter, r *http.Request) ([]byte, string, error) { var filename string var u = &User{} reqJSON := IsJSON(r) if reqJSON { // Use given Authorization header accessToken := r.Header.Get("Authorization") if accessToken == "" { return nil, filename, ErrNoAccessToken } userID := app.db.GetUserID(accessToken) if userID == -1 { return nil, filename, ErrBadAccessToken } var err error u, err = app.db.GetUserByID(userID) if err != nil { return nil, filename, impart.HTTPError{http.StatusInternalServerError, "Unable to retrieve requested user."} } } else { // Use user cookie session, err := app.sessionStore.Get(r, cookieName) if err != nil { // The cookie should still save, even if there's an error. log.Error("Session: %v; ignoring", err) } val := session.Values[cookieUserVal] var ok bool if u, ok = val.(*User); !ok { return nil, filename, ErrNotLoggedIn } } filename = u.Username + "-posts-" + time.Now().Truncate(time.Second).UTC().Format("200601021504") // Fetch data we're exporting var err error var data []byte posts, err := app.db.GetUserPosts(u) if err != nil { return data, filename, err } // Export as CSV if strings.HasSuffix(r.URL.Path, ".csv") { data = exportPostsCSV(app.cfg.App.Host, u, posts) return data, filename, err } if strings.HasSuffix(r.URL.Path, ".zip") { data = exportPostsZip(u, posts) return data, filename, err } if r.FormValue("pretty") == "1" { data, err = json.MarshalIndent(posts, "", "\t") } else { data, err = json.Marshal(posts) } return data, filename, err } func viewExportFull(app *App, w http.ResponseWriter, r *http.Request) ([]byte, string, error) { var err error filename := "" u := getUserSession(app, r) if u == nil { return nil, filename, ErrNotLoggedIn } filename = u.Username + "-" + time.Now().Truncate(time.Second).UTC().Format("200601021504") exportUser := compileFullExport(app, u) var data []byte if r.FormValue("pretty") == "1" { data, err = json.MarshalIndent(exportUser, "", "\t") } else { data, err = json.Marshal(exportUser) } return data, filename, err } func viewMeAPI(app *App, w http.ResponseWriter, r *http.Request) error { reqJSON := IsJSON(r) uObj := struct { ID int64 `json:"id,omitempty"` Username string `json:"username,omitempty"` }{} var err error if reqJSON { _, uObj.Username, err = app.db.GetUserDataFromToken(r.Header.Get("Authorization")) if err != nil { return err } } else { u := getUserSession(app, r) if u == nil { return impart.WriteSuccess(w, uObj, http.StatusOK) } uObj.Username = u.Username } return impart.WriteSuccess(w, uObj, http.StatusOK) } func viewMyPostsAPI(app *App, u *User, w http.ResponseWriter, r *http.Request) error { reqJSON := IsJSON(r) if !reqJSON { return ErrBadRequestedType } var err error p := GetPostsCache(u.ID) if p == nil { userPostsCache.Lock() if userPostsCache.users[u.ID].ready == nil { userPostsCache.users[u.ID] = postsCacheItem{ready: make(chan struct{})} userPostsCache.Unlock() p, err = app.db.GetUserPosts(u) if err != nil { return err } CachePosts(u.ID, p) } else { userPostsCache.Unlock() <-userPostsCache.users[u.ID].ready p = GetPostsCache(u.ID) } } return impart.WriteSuccess(w, p, http.StatusOK) } func viewMyCollectionsAPI(app *App, u *User, w http.ResponseWriter, r *http.Request) error { reqJSON := IsJSON(r) if !reqJSON { return ErrBadRequestedType } p, err := app.db.GetCollections(u, app.cfg.App.Host) if err != nil { return err } return impart.WriteSuccess(w, p, http.StatusOK) } func viewArticles(app *App, u *User, w http.ResponseWriter, r *http.Request) error { p, err := app.db.GetAnonymousPosts(u) if err != nil { log.Error("unable to fetch anon posts: %v", err) } // nil-out AnonymousPosts slice for easy detection in the template if p != nil && len(*p) == 0 { p = nil } f, err := getSessionFlashes(app, w, r, nil) if err != nil { log.Error("unable to fetch flashes: %v", err) } c, err := app.db.GetPublishableCollections(u, app.cfg.App.Host) if err != nil { log.Error("unable to fetch collections: %v", err) } suspended, err := app.db.IsUserSuspended(u.ID) if err != nil { log.Error("view articles: %v", err) } d := struct { *UserPage AnonymousPosts *[]PublicPost Collections *[]Collection Suspended bool }{ UserPage: NewUserPage(app, r, u, u.Username+"'s Posts", f), AnonymousPosts: p, Collections: c, Suspended: suspended, } d.UserPage.SetMessaging(u) w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") w.Header().Set("Expires", "Thu, 04 Oct 1990 20:00:00 GMT") showUserPage(w, "articles", d) return nil } func viewCollections(app *App, u *User, w http.ResponseWriter, r *http.Request) error { c, err := app.db.GetCollections(u, app.cfg.App.Host) if err != nil { log.Error("unable to fetch collections: %v", err) return fmt.Errorf("No collections") } f, _ := getSessionFlashes(app, w, r, nil) uc, _ := app.db.GetUserCollectionCount(u.ID) // TODO: handle any errors suspended, err := app.db.IsUserSuspended(u.ID) if err != nil { log.Error("view collections %v", err) return fmt.Errorf("view collections: %v", err) } d := struct { *UserPage Collections *[]Collection UsedCollections, TotalCollections int NewBlogsDisabled bool Suspended bool }{ UserPage: NewUserPage(app, r, u, u.Username+"'s Blogs", f), Collections: c, UsedCollections: int(uc), NewBlogsDisabled: !app.cfg.App.CanCreateBlogs(uc), Suspended: suspended, } d.UserPage.SetMessaging(u) showUserPage(w, "collections", d) return nil } func viewEditCollection(app *App, u *User, w http.ResponseWriter, r *http.Request) error { vars := mux.Vars(r) c, err := app.db.GetCollection(vars["collection"]) if err != nil { return err } if c.OwnerID != u.ID { return ErrCollectionNotFound } suspended, err := app.db.IsUserSuspended(u.ID) if err != nil { log.Error("view edit collection %v", err) return fmt.Errorf("view edit collection: %v", err) } flashes, _ := getSessionFlashes(app, w, r, nil) obj := struct { *UserPage *Collection Suspended bool }{ UserPage: NewUserPage(app, r, u, "Edit "+c.DisplayTitle(), flashes), Collection: c, Suspended: suspended, } showUserPage(w, "collection", obj) return nil } func updateSettings(app *App, w http.ResponseWriter, r *http.Request) error { reqJSON := IsJSON(r) var s userSettings var u *User var sess *sessions.Session var err error if reqJSON { accessToken := r.Header.Get("Authorization") if accessToken == "" { return ErrNoAccessToken } u, err = app.db.GetAPIUser(accessToken) if err != nil { return ErrBadAccessToken } decoder := json.NewDecoder(r.Body) err := decoder.Decode(&s) if err != nil { log.Error("Couldn't parse settings JSON request: %v\n", err) return ErrBadJSON } // Prevent all username updates // TODO: support changing username via JSON API request s.Username = "" } else { u, sess = getUserAndSession(app, r) if u == nil { return ErrNotLoggedIn } err := r.ParseForm() if err != nil { log.Error("Couldn't parse settings form request: %v\n", err) return ErrBadFormData } err = app.formDecoder.Decode(&s, r.PostForm) if err != nil { log.Error("Couldn't decode settings form request: %v\n", err) return ErrBadFormData } } // Do update postUpdateReturn := r.FormValue("return") redirectTo := "/me/settings" if s.IsLogOut { redirectTo += "?logout=1" } else if postUpdateReturn != "" { redirectTo = postUpdateReturn } // Only do updates on values we need if s.Username != "" && s.Username == u.Username { // Username hasn't actually changed; blank it out s.Username = "" } err = app.db.ChangeSettings(app, u, &s) if err != nil { if reqJSON { return err } if err, ok := err.(impart.HTTPError); ok { addSessionFlash(app, w, r, err.Message, nil) } } else { // Successful update. if reqJSON { return impart.WriteSuccess(w, u, http.StatusOK) } if s.IsLogOut { redirectTo = "/me/logout" } else { sess.Values[cookieUserVal] = u.Cookie() addSessionFlash(app, w, r, "Account updated.", nil) } } w.Header().Set("Location", redirectTo) w.WriteHeader(http.StatusFound) return nil } func updatePassphrase(app *App, w http.ResponseWriter, r *http.Request) error { accessToken := r.Header.Get("Authorization") if accessToken == "" { return ErrNoAccessToken } curPass := r.FormValue("current") newPass := r.FormValue("new") // Ensure a new password is given (always required) if newPass == "" { return impart.HTTPError{http.StatusBadRequest, "Provide a new password."} } userID, sudo := app.db.GetUserIDPrivilege(accessToken) if userID == -1 { return ErrBadAccessToken } // Ensure a current password is given if the access token doesn't have sudo // privileges. if !sudo && curPass == "" { return impart.HTTPError{http.StatusBadRequest, "Provide current password."} } // Hash the new password hashedPass, err := auth.HashPass([]byte(newPass)) if err != nil { return impart.HTTPError{http.StatusInternalServerError, "Could not create password hash."} } // Do update err = app.db.ChangePassphrase(userID, sudo, curPass, hashedPass) if err != nil { return err } return impart.WriteSuccess(w, struct{}{}, http.StatusOK) } func viewStats(app *App, u *User, w http.ResponseWriter, r *http.Request) error { var c *Collection var err error vars := mux.Vars(r) alias := vars["collection"] if alias != "" { c, err = app.db.GetCollection(alias) if err != nil { return err } if c.OwnerID != u.ID { return ErrCollectionNotFound } } topPosts, err := app.db.GetTopPosts(u, alias) if err != nil { log.Error("Unable to get top posts: %v", err) return err } flashes, _ := getSessionFlashes(app, w, r, nil) titleStats := "" if c != nil { titleStats = c.DisplayTitle() + " " } suspended, err := app.db.IsUserSuspended(u.ID) if err != nil { log.Error("view stats: %v", err) return err } obj := struct { *UserPage VisitsBlog string Collection *Collection TopPosts *[]PublicPost APFollowers int Suspended bool }{ UserPage: NewUserPage(app, r, u, titleStats+"Stats", flashes), VisitsBlog: alias, Collection: c, TopPosts: topPosts, Suspended: suspended, } if app.cfg.App.Federation { folls, err := app.db.GetAPFollowers(c) if err != nil { return err } obj.APFollowers = len(*folls) } showUserPage(w, "stats", obj) return nil } func viewSettings(app *App, u *User, w http.ResponseWriter, r *http.Request) error { fullUser, err := app.db.GetUserByID(u.ID) if err != nil { log.Error("Unable to get user for settings: %s", err) return impart.HTTPError{http.StatusInternalServerError, "Unable to retrieve user data. The humans have been alerted."} } passIsSet, err := app.db.IsUserPassSet(u.ID) if err != nil { log.Error("Unable to get isUserPassSet for settings: %s", err) return impart.HTTPError{http.StatusInternalServerError, "Unable to retrieve user data. The humans have been alerted."} } flashes, _ := getSessionFlashes(app, w, r, nil) obj := struct { *UserPage Email string HasPass bool IsLogOut bool Suspended bool }{ UserPage: NewUserPage(app, r, u, "Account Settings", flashes), Email: fullUser.EmailClear(app.keys), HasPass: passIsSet, IsLogOut: r.FormValue("logout") == "1", Suspended: fullUser.IsSilenced(), } showUserPage(w, "settings", obj) return nil } func saveTempInfo(app *App, key, val string, r *http.Request, w http.ResponseWriter) error { session, err := app.sessionStore.Get(r, "t") if err != nil { return ErrInternalCookieSession } session.Values[key] = val err = session.Save(r, w) if err != nil { log.Error("Couldn't saveTempInfo for key-val (%s:%s): %v", key, val, err) } return err } func getTempInfo(app *App, key string, r *http.Request, w http.ResponseWriter) string { session, err := app.sessionStore.Get(r, "t") if err != nil { return "" } // Get the information var s = "" var ok bool if s, ok = session.Values[key].(string); !ok { return "" } // Delete cookie session.Options.MaxAge = -1 err = session.Save(r, w) if err != nil { log.Error("Couldn't erase temp data for key %s: %v", key, err) } // Return value return s } func prepareUserEmail(input string, emailKey []byte) zero.String { email := zero.NewString("", input != "") if len(input) > 0 { encEmail, err := data.Encrypt(emailKey, input) if err != nil { log.Error("Unable to encrypt email: %s\n", err) } else { email.String = string(encEmail) } } return email } diff --git a/config/config.go b/config/config.go index 996c1df..2616e9e 100644 --- a/config/config.go +++ b/config/config.go @@ -1,206 +1,212 @@ /* * Copyright © 2018-2019 A Bunch Tell LLC. * * This file is part of WriteFreely. * * WriteFreely is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, included * in the LICENSE file in this source code package. */ // Package config holds and assists in the configuration of a writefreely instance. package config import ( "gopkg.in/ini.v1" "strings" ) const ( // FileName is the default configuration file name FileName = "config.ini" UserNormal UserType = "user" UserAdmin = "admin" ) type ( UserType string // ServerCfg holds values that affect how the HTTP server runs ServerCfg struct { HiddenHost string `ini:"hidden_host"` Port int `ini:"port"` Bind string `ini:"bind"` TLSCertPath string `ini:"tls_cert_path"` TLSKeyPath string `ini:"tls_key_path"` Autocert bool `ini:"autocert"` TemplatesParentDir string `ini:"templates_parent_dir"` StaticParentDir string `ini:"static_parent_dir"` PagesParentDir string `ini:"pages_parent_dir"` KeysParentDir string `ini:"keys_parent_dir"` + HashSeed string `ini:"hash_seed"` + Dev bool `ini:"-"` } // DatabaseCfg holds values that determine how the application connects to a datastore DatabaseCfg struct { Type string `ini:"type"` FileName string `ini:"filename"` User string `ini:"username"` Password string `ini:"password"` Database string `ini:"database"` Host string `ini:"host"` Port int `ini:"port"` } WriteAsOauthCfg struct { - ClientID string `ini:"client_id"` - ClientSecret string `ini:"client_secret"` - AuthLocation string `ini:"auth_location"` - TokenLocation string `ini:"token_location"` - InspectLocation string `ini:"inspect_location"` + ClientID string `ini:"client_id"` + ClientSecret string `ini:"client_secret"` + AuthLocation string `ini:"auth_location"` + TokenLocation string `ini:"token_location"` + InspectLocation string `ini:"inspect_location"` + CallbackProxy string `ini:"callback_proxy"` + CallbackProxyAPI string `ini:"callback_proxy_api"` } SlackOauthCfg struct { - ClientID string `ini:"client_id"` - ClientSecret string `ini:"client_secret"` - TeamID string `ini:"team_id"` + ClientID string `ini:"client_id"` + ClientSecret string `ini:"client_secret"` + TeamID string `ini:"team_id"` + CallbackProxy string `ini:"callback_proxy"` + CallbackProxyAPI string `ini:"callback_proxy_api"` } // AppCfg holds values that affect how the application functions AppCfg struct { SiteName string `ini:"site_name"` SiteDesc string `ini:"site_description"` Host string `ini:"host"` // Site appearance Theme string `ini:"theme"` Editor string `ini:"editor"` JSDisabled bool `ini:"disable_js"` WebFonts bool `ini:"webfonts"` Landing string `ini:"landing"` SimpleNav bool `ini:"simple_nav"` WFModesty bool `ini:"wf_modesty"` // Site functionality Chorus bool `ini:"chorus"` DisableDrafts bool `ini:"disable_drafts"` // Users SingleUser bool `ini:"single_user"` OpenRegistration bool `ini:"open_registration"` MinUsernameLen int `ini:"min_username_len"` MaxBlogs int `ini:"max_blogs"` // Federation Federation bool `ini:"federation"` PublicStats bool `ini:"public_stats"` // Access Private bool `ini:"private"` // Additional functions LocalTimeline bool `ini:"local_timeline"` UserInvites string `ini:"user_invites"` // Defaults DefaultVisibility string `ini:"default_visibility"` } // Config holds the complete configuration for running a writefreely instance Config struct { Server ServerCfg `ini:"server"` Database DatabaseCfg `ini:"database"` App AppCfg `ini:"app"` SlackOauth SlackOauthCfg `ini:"oauth.slack"` WriteAsOauth WriteAsOauthCfg `ini:"oauth.writeas"` } ) // New creates a new Config with sane defaults func New() *Config { c := &Config{ Server: ServerCfg{ Port: 8080, Bind: "localhost", /* IPV6 support when not using localhost? */ }, App: AppCfg{ Host: "http://localhost:8080", Theme: "write", WebFonts: true, SingleUser: true, MinUsernameLen: 3, MaxBlogs: 1, Federation: true, PublicStats: true, }, } c.UseMySQL(true) return c } // UseMySQL resets the Config's Database to use default values for a MySQL setup. func (cfg *Config) UseMySQL(fresh bool) { cfg.Database.Type = "mysql" if fresh { cfg.Database.Host = "localhost" cfg.Database.Port = 3306 } } // UseSQLite resets the Config's Database to use default values for a SQLite setup. func (cfg *Config) UseSQLite(fresh bool) { cfg.Database.Type = "sqlite3" if fresh { cfg.Database.FileName = "writefreely.db" } } // IsSecureStandalone returns whether or not the application is running as a // standalone server with TLS enabled. func (cfg *Config) IsSecureStandalone() bool { return cfg.Server.Port == 443 && cfg.Server.TLSCertPath != "" && cfg.Server.TLSKeyPath != "" } func (ac *AppCfg) LandingPath() string { if !strings.HasPrefix(ac.Landing, "/") { return "/" + ac.Landing } return ac.Landing } // Load reads the given configuration file, then parses and returns it as a Config. func Load(fname string) (*Config, error) { if fname == "" { fname = FileName } cfg, err := ini.Load(fname) if err != nil { return nil, err } // Parse INI file uc := &Config{} err = cfg.MapTo(uc) if err != nil { return nil, err } return uc, nil } // Save writes the given Config to the given file. func Save(uc *Config, fname string) error { cfg := ini.Empty() err := ini.ReflectFrom(cfg, uc) if err != nil { return err } if fname == "" { fname = FileName } return cfg.SaveTo(fname) } diff --git a/less/core.less b/less/core.less index 8844c84..3669d76 100644 --- a/less/core.less +++ b/less/core.less @@ -1,1520 +1,1521 @@ @primary: rgb(114, 120, 191); @secondary: rgb(114, 191, 133); @subheaders: #444; @headerTextColor: black; @sansFont: 'Open Sans', 'Segoe UI', Tahoma, Arial, sans-serif; @serifFont: Lora, 'Palatino Linotype', 'Book Antiqua', 'New York', 'DejaVu serif', serif; @monoFont: Hack, consolas, Menlo-Regular, Menlo, Monaco, 'ubuntu mono', monospace, monospace; @dangerCol: #e21d27; @errUrgentCol: #ecc63c; @proSelectedCol: #71D571; @textLinkColor: rgb(0, 0, 238); body { font-family: @serifFont; font-size-adjust: 0.5; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; background-color: white; color: #111; h1, header h2 { a { color: @headerTextColor; .transition-duration(0.2s); &:hover { color: #303030; text-decoration: none; } } } h1, h2, h3 { line-height: 1.2; } &#post article, &#collection article p, &#subpage article p { display: block; unicode-bidi: embed; white-space: pre; } &#post { #wrapper, pre { max-width: 40em; margin: 0 auto; a:hover { text-decoration: underline; } } blockquote { p + p { margin: -2em 0 0.5em; } } article { margin-bottom: 2em !important; h1, h2, h3, h4, h5, h6, p, ul, ol, code { display: inline; margin: 0; } hr + p, ol, ul { display: block; margin-top: -1rem; margin-bottom: -1rem; } ol, ul { margin: 2rem 0 -1rem; ol, ul { margin: 1.25rem 0 -0.5rem; } } li { margin-top: -0.5rem; margin-bottom: -0.5rem; } h2#title { .article-title; } h1 { font-size: 1.5em; } h2 { font-size: 1.17em; } } header { nav { span, a { &.pinned { &.selected { font-weight: bold; } &+.views { margin-left: 2em; } } } } } .owner-visible { display: none; } } &#post, &#collection, &#subpage { code { .article-code; } img, video, audio { max-width: 100%; } audio { width: 100%; white-space: initial; } pre { .code-block; code { background: transparent; border: 0; padding: 0; font-size: 1em; white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ } } blockquote { .article-blockquote; } article { hr { margin-top: 0; margin-bottom: 0; } p.badge { background-color: #aaa; display: inline-block; padding: 0.25em 0.5em; margin: 0; float: right; color: white; .rounded(.25em); } } header { nav { span, a { &.pinned { &+.pinned { margin-left: 1.5em; } } } } } footer { nav { a { margin-top: 0; } } } } &#collection { #welcome, .access { margin: 0 auto; max-width: 35em; h2 { font-weight: normal; margin-bottom: 1em; } p { font-size: 1.2em; line-height: 1.6; } } .access { margin: 8em auto; text-align: center; h2, ul.errors { font-size: 1.2em; margin-bottom: 1.5em !important; } } header { padding: 0 1em; text-align: center; max-width: 50em; margin: 3em auto 4em; .writeas-prefix { a { color: #aaa; } display: block; margin-bottom: 0.5em; } nav { display: block; margin: 1em 0; a:first-child { margin: 0; } } } nav#manage { position: absolute; top: 1em; left: 1.5em; li a.write { font-family: @serifFont; padding-top: 0.2em; padding-bottom: 0.2em; } } pre { line-height: 1.5; } } &#subpage { #wrapper { h1 { font-size: 2.5em; letter-spacing: -2px; padding: 0 2rem 2rem; } } } &#post { pre { font-size: 0.75em; } } &#collection, &#subpage { #wrapper { margin-left: auto; margin-right: auto; article { margin-bottom: 4em; &:hover { .hidden { .opacity(1); } } } h2 { margin-top: 0em; margin-bottom: 0.25em; &+time { display: block; margin-top: 0.25em; margin-bottom: 0.25em; } } time { font-size: 1.1em; &+p { margin-top: 0.25em; } } footer { text-align: left; padding: 0; } } #paging { overflow: visible; padding: 1em 6em 0; } a.read-more { color: #666; } } &#me #official-writing { h2 { font-weight: normal; a { font-size: 0.6em; margin-left: 1em; } a[name] { margin-left: 0; } a:link, a:visited { color: @textLinkColor; } a:hover { text-decoration: underline; } } } &#promo { div.heading { margin: 8em 0; } div.heading, div.attention-form { h1 { font-size: 3.5em; } input { padding-left: 0.75em; padding-right: 0.75em; &[type=email] { max-width: 16em; } &[type=submit] { padding-left: 1.5em; padding-right: 1.5em; } } } h2 { margin-bottom: 0; font-size: 1.8em; font-weight: normal; span.write-as { color: black; } &.soon { color: lighten(@subheaders, 50%); span { &.write-as { color: lighten(#000, 50%); } &.note { color: lighten(#333, 50%); font-variant: small-caps; margin-left: 0.5em; } } } } .half-col a { margin-left: 1em; margin-right: 1em; } } nav#top-nav { display: inline; position: absolute; top: 1.5em; right: 1.5em; font-size: 0.95rem; font-family: @sansFont; text-transform: uppercase; a { color: #777; } a + a { margin-left: 1em; } } footer { nav, ul { a { display: inline-block; margin-top: 0.8em; .transition-duration(0.1s); text-decoration: none; + a { margin-left: 0.8em; } &:link, &:visited { color: #999; } &:hover { color: #666; text-decoration: none; } } } a.home { &:link, &:visited { color: #333; } font-weight: bold; text-decoration: none; &:hover { color: #000; } } ul { list-style: none; text-align: left; padding-left: 0 !important; margin-left: 0 !important; .icons img { height: 16px; width: 16px; fill: #999; } } } } nav#full-nav { margin: 0; .left-side { display: inline-block; a:first-child { margin-left: 0; } } .right-side { float: right; } } nav#full-nav a.simple-btn, .tool button { font-family: @sansFont; border: 1px solid #ccc !important; padding: .5rem 1rem; margin: 0; .rounded(.25em); text-decoration: none; } .post-title { a { &:link { color: #333; } &:visited { color: #444; } } time, time a:link, time a:visited, &+.time { color: #999; } } .hidden { -moz-transition-property: opacity; -webkit-transition-property: opacity; -o-transition-property: opacity; transition-property: opacity; .transition-duration(0.4s); .opacity(0); } a { text-decoration: none; &:hover { text-decoration: underline; } &.subdued { color: #999; &:hover { border-bottom: 1px solid #999; text-decoration: none; } } &.danger { color: @dangerCol; font-size: 0.86em; } &.simple-cta { text-decoration: none; border-bottom: 1px solid #ccc; color: #333; padding-bottom: 2px; &:hover { text-decoration: none; } } &.action-btn { font-family: @sansFont; text-transform: uppercase; .rounded(.25em); background-color: red; color: white; font-weight: bold; padding: 0.5em 0.75em; &:hover { background-color: lighten(#f00, 5%); text-decoration: none; } } &.hashtag:hover { text-decoration: none; span + span { text-decoration: underline; } } &.hashtag { span:first-child { color: #999; margin-right: 0.1em; font-size: 0.86em; text-decoration: none; } } } abbr { border-bottom: 1px dotted #999; text-decoration: none; cursor: help; } body#collection article p, body#subpage article p { .article-p; } pre, body#post article, #post .alert, #subpage .alert, body#collection article, body#subpage article, body#subpage #wrapper h1 { max-width: 40rem; margin: 0 auto; } #collection header .alert, #post .alert, #subpage .alert { margin-bottom: 1em; p { text-align: left; line-height: 1.4; } } textarea, pre, body#post article, body#collection article p { &.norm, &.sans, &.wrap { line-height: 1.4em; white-space: pre-wrap; /* CSS 3 */ white-space: -moz-pre-wrap; /* Mozilla, since 1999 */ white-space: -pre-wrap; /* Opera 4-6 */ white-space: -o-pre-wrap; /* Opera 7 */ word-wrap: break-word; /* Internet Explorer 5.5+ */ } } textarea, pre, body#post article, body#collection article, body#subpage article, span, .font { &.norm { font-family: @serifFont; } &.sans { font-family: @sansFont; } &.mono, &.wrap, &.code { font-family: @monoFont; } &.mono, &.code { max-width: none !important; } } textarea { &.section { border: 1px solid #ccc; padding: 0.65em 0.75em; .rounded(.25em); &.codable { height: 12em; resize: vertical; } } } .ace_editor { height: 12em; border: 1px solid #333; max-width: initial; width: 100%; font-size: 0.86em !important; border: 1px solid #ccc; padding: 0.65em 0.75em; margin: 0; .rounded(.25em); } p { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; &.intro { font-size: 1.25em; text-align: center; } &.upgrade-prompt { font-size: 0.9em; color: #444; } &.text-cta { font-size: 1.2em; text-align: center; margin-bottom: 0.5em; &+ p { text-align: center; font-size: 0.7em; margin-top: 0; color: #666; } } &.error { font-style: italic; color: @errUrgentCol; } &.headeresque { font-size: 2em; } } table.classy { width: 95%; border-collapse: collapse; margin-bottom: 2em; tr + tr { border-top: 1px solid #ccc; } th { text-transform: uppercase; font-weight: normal; font-size: 95%; font-family: @sansFont; padding: 1rem 0.75rem; text-align: center; } td { height: 3.5rem; } p { margin-top: 0 !important; margin-bottom: 0 !important; } &.export { .disabled { color: #999; } .disabled, a { text-transform: lowercase; } } } body#collection article, body#subpage article { padding-top: 0; padding-bottom: 0; .book { h2 { font-size: 1.4em; } a.hidden.action { color: #666; float: right; font-size: 1em; margin-left: 1em; margin-bottom: 1em; } } } body#post article { p.badge { font-size: 0.9em; } } article { h2.post-title a[rel=nofollow]::after { content: '\a0 \2934'; } } table.downloads { width: 100%; td { text-align: center; } img.os { width: 48px; vertical-align: middle; margin-bottom: 6px; } } select.inputform, textarea.inputform { border: 1px solid #999; } -input, button, select.inputform, textarea.inputform { +input, button, select.inputform, textarea.inputform, a.btn { padding: 0.5em; font-family: @serifFont; font-size: 100%; .rounded(.25em); - &[type=submit], &.submit { + &[type=submit], &.submit, &.cta { border: 1px solid @primary; background: @primary; color: white; .transition(0.2s); &:hover { background-color: lighten(@primary, 3%); + text-decoration: none; } &:disabled { cursor: default; background-color: desaturate(@primary, 100%) !important; border-color: desaturate(@primary, 100%) !important; } } &.error[type=text], textarea.error { -webkit-transition: all 0.30s ease-in-out; -moz-transition: all 0.30s ease-in-out; -ms-transition: all 0.30s ease-in-out; -o-transition: all 0.30s ease-in-out; outline: none; } &.danger { border: 1px solid @dangerCol; background: @dangerCol; color: white; &:hover { background-color: lighten(@dangerCol, 3%); } } &.error[type=text]:focus, textarea.error:focus { box-shadow: 0 0 5px @errUrgentCol; border: 1px solid @errUrgentCol; } } div.flat-select { display: inline-block; position: relative; select { border: 0; background: 0; -webkit-appearance: none; -moz-appearance: none; appearance: none; position: absolute; top: 0; left: 0; right: 0; bottom: 0; width: 100%; height: 100%; opacity: 0; } &.action { &:hover { label { text-decoration: underline; } } label, select { cursor: pointer; } } } input { &.underline{ border: none; border-bottom: 1px solid #ccc; padding: 0 .2em .2em; font-size: 0.9em; color: #333; } &.inline { padding: 0.2rem 0.2rem; margin-left: 0; font-size: 1em; border: 0 !important; border-bottom: 1px solid #999 !important; width: 7em; .rounded(0); } &[type=tel], &[type=text], &[type=email], &[type=password] { border: 1px solid #999; } &.boxy { border: 1px solid #999 !important; } } #beta, .content-container { max-width: 50em; margin: 0 auto 3em; font-size: 1.2em; &.tight { max-width: 30em; } &.snug { max-width: 40em; } &.regular { font-size: 1em; } .app { + .app { margin-top: 1.5em; } h2 { margin-bottom: 0.25em; } p { margin-top: 0.25em; } } h2.intro { font-weight: normal; } p { line-height: 1.4; } li { margin: 0.3em 0; } h2 { &.light { font-weight: normal; } a { .transition-duration(0.2s); -moz-transition-property: color; -webkit-transition-property: color; -o-transition-property: color; transition-property: color; &:link, &:visited, &:hover { color: @subheaders; } &:hover { color: lighten(@subheaders, 10%); text-decoration: none; } } } } .content-container { &#pricing { button { cursor: pointer; color: white; margin-top: 1em; margin-bottom: 1em; padding-left: 1.5em; padding-right: 1.5em; border: 0; background: @primary; .rounded(.25em); .transition(0.2s); &:hover { background-color: lighten(@primary, 5%); } &.unselected { cursor: pointer; } } h2 span { font-weight: normal; } .half { margin: 0 0 1em 0; text-align: center; } } div.features { margin-top: 1.5em; text-align: center; font-size: 0.86em; ul { text-align: left; max-width: 26em; margin-left: auto !important; margin-right: auto !important; li.soon, span.soon { color: lighten(#111, 40%); } } } div.blurbs { >h2 { text-align: center; color: #333; font-weight: normal; } p.price { font-size: 1.2em; margin-bottom: 0; color: #333; margin-top: 0.5em; &+p { margin-top: 0; font-size: 0.8em; } } p.text-cta { font-size: 1em; } } } footer div.blurbs { display: flex; flex-flow: row; flex-wrap: wrap; } div.blurbs { .half, .third, .fourth { font-size: 0.86em; h3 { font-weight: normal; } p, ul { color: #595959; } hr { margin: 1em 0; } } .half { padding: 0 1em 0 0; width: ~"calc(50% - 1em)"; &+.half { padding: 0 0 0 1em; } } .third { padding: 0; width: ~"calc(33% - 1em)"; &+.third { padding: 0 0 0 1em; } } .fourth { flex: 1 1 25%; -webkit-flex: 1 1 25%; h3 { margin-bottom: 0.5em; } ul { margin-top: 0.5em; } } } .contain-me { text-align: left; margin: 0 auto 4em; max-width: 50em; h2 + p, h2 + p + p, p.describe-me { margin-left: 1.5em; margin-right: 1.5em; color: #333; } } footer.contain-me { font-size: 1.1em; } #official-writing, #wrapper { h2, h3, h4 { color: @subheaders; } ul { &.collections { margin-left: 0; li { &.collection { a.title { &:link, &:visited { color: @headerTextColor; } } } a.create { color: #444; } } & + p { margin-top: 2em; margin-left: 1em; } } } } #official-writing, #wrapper { h2 { &.major { color: #222; } &.bugfix { color: #666; } +.android-version { a { color: #999; &:hover { text-decoration: underline; } } } } } li { line-height: 1.4; .item-desc, .prog-lang { font-size: 0.6em; font-family: 'Open Sans', sans-serif; font-weight: bold; margin-left: 0.5em; margin-right: 0.5em; text-transform: uppercase; color: #999; } } .success { color: darken(@proSelectedCol, 20%); } .alert { padding: 1em; margin-bottom: 1.25em; border: 1px solid transparent; .rounded(.25em); &.info { color: #31708f; background-color: #d9edf7; border-color: #bce8f1; } &.success { color: #3c763d; background-color: #dff0d8; border-color: #d6e9c6; } p { margin: 0; &+p { margin-top: 0.5em; } } p.dismiss { font-family: @sansFont; text-align: right; font-size: 0.86em; text-transform: uppercase; } } ul.errors { padding: 0; text-indent: 0; li.urgent { list-style: none; font-style: italic; text-align: center; color: @errUrgentCol; a:link, a:visited { color: purple; } } li.info { list-style: none; font-size: 1.1em; text-align: center; } } body#pad #target a.upgrade-prompt { padding-left: 1em; padding-right: 1em; text-align: center; font-style: italic; color: @primary; } body#pad-sub #posts, .atoms { margin-top: 1.5em; h3 { margin-bottom: 0.25em; &+ h4 { margin-top: 0.25em; margin-bottom: 0.5em; &+ p { margin-top: 0.5em; } } .electron { font-weight: normal; margin-left: 0.5em; } } h3, h4 { a { .transition-duration(0.2s); -moz-transition-property: color; -webkit-transition-property: color; -o-transition-property: color; transition-property: color; } } h4 { font-size: 0.9em; font-weight: normal; } date, .electron { margin-right: 0.5em; } .action { font-size: 1em; } #more-posts p { text-align: center; font-size: 1.1em; } p { font-size: 0.86em; } .error { display: inline-block; font-size: 0.8em; font-style: italic; color: @errUrgentCol; strong { font-style: normal; } } .error + nav { display: inline-block; font-size: 0.8em; margin-left: 1em; a + a { margin-left: 0.75em; } } } h2 { a, time { &+.action { margin-left: 0.5em; } } } .action { font-size: 0.7em; font-weight: normal; font-family: @serifFont; &+ .action { margin-left: 0.5em; } &.new-post { font-weight: bold; } } article.moved { p { font-size: 1.2em; color: #999; } } span.as { .opacity(0.2); font-weight: normal; } span.ras { .opacity(0.6); font-weight: normal; } header { nav { .username { font-size: 2em; font-weight: normal; color: #555; } &#user-nav { margin-left: 0; & > a, .tabs > a { &.selected { cursor: default; font-weight: bold; &:hover { text-decoration: none; } } & + a { margin-left: 2em; } } a { font-size: 1.2em; font-family: @sansFont; span { font-size: 0.7em; color: #999; text-transform: uppercase; margin-left: 0.5em; margin-right: 0.5em; } &.title { font-size: 1.6em; font-family: @serifFont; font-weight: bold; } } nav > ul > li:first-child { &> a { display: inline-block; } img { position: relative; top: -0.5em; right: 0.3em; } } ul ul { font-size: 0.8em; a { padding-top: 0.25em; padding-bottom: 0.25em; } } li { line-height: 1.5; } } &.tabs { margin: 0 0 0 1em; } &+ nav.tabs { margin: 0; } } &.singleuser { margin: 0.5em 0.25em; nav#user-nav { nav > ul > li:first-child { img { top: -0.75em; } } } } .dash-nav { font-weight: bold; } } li#create-collection { display: none; h4 { margin-top: 0px; margin-bottom: 0px; } input[type=submit] { margin-left: 0.5em; } } #collection-options { .option { textarea { font-size: 0.86em; font-family: @monoFont; } .section > p.explain { font-size: 0.8em; } } } .img-placeholder { text-align: center; img { max-width: 100%; } } dl { &.admin-dl-horizontal { dt { font-weight: bolder; width: 360px; } dd { line-height: 1.5; } } } dt { float: left; clear: left; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } form { dt, dd { padding: 0.5rem 0; } dt { line-height: 1.8; } dd { font-size: 0.86em; line-height: 2; } } div.row { display: flex; align-items: center; > div { flex: 1; } } @media all and (max-width: 450px) { body#post { header { nav { .xtra-feature { display: none; } } } } } @media all and (min-width: 1280px) { body#promo { div.heading { margin: 10em 0; } } } @media all and (min-width: 1600px) { body#promo { div.heading { margin: 14em 0; } } } @media all and (max-width: 900px) { .half.big { padding: 0 !important; width: 100% !important; } .third { padding: 0 !important; float: none; width: 100% !important; p.introduction { font-size: 0.86em; } } div.blurbs { .fourth { flex: 1 1 15em; -webkit-flex: 1 1 15em; } } .blurbs .third, .blurbs .half { p, ul { text-align: left; } } .half-col, .big { float: none; text-align: center; &+.half-col, &+.big { margin-top: 4em !important; margin-left: 0; } } #beta, .content-container { font-size: 1.15em; } } @media all and (max-width: 600px) { div.row { flex-direction: column; } .half { padding: 0 !important; width: 100% !important; } .third { width: 100% !important; float: none; } body#promo { div.heading { margin: 6em 0; } h2 { font-size: 1.6em; } .half-col a + a { margin-left: 1em; } .half-col a.channel { margin-left: auto !important; margin-right: auto !important; } } ul.add-integrations { li { display: list-item; &+ li { margin-left: 0; } } } } @media all and (max-height: 500px) { body#promo { div.heading { margin: 5em 0; } } } @media all and (max-height: 400px) { body#promo { div.heading { margin: 0em 0; } } } /* Smartphones (portrait and landscape) ----------- */ @media only screen and (min-device-width : 320px) and (max-device-width : 480px) { header { .opacity(1); } } /* Smartphones (portrait) ----------- */ @media only screen and (max-width : 320px) { .content-container#pricing { .half { float: none; width: 100%; } } header { .opacity(1); } } /* iPads (portrait and landscape) ----------- */ @media only screen and (min-device-width : 768px) and (max-device-width : 1024px) { header { .opacity(1); } } @media (pointer: coarse) { body footer nav a:not(.pubd) { padding: 0.8em 1em; margin-left: 0; margin-top: 0; } } @media print { h1 { page-break-before: always; } h1, h2, h3, h4, h5, h6 { page-break-after: avoid; } table, figure { page-break-inside: avoid; } header, footer { display: none; } article#post-body { margin-top: 2em; margin-left: 0; margin-right: 0; } hr { border: 1px solid #ccc; } } .code-block { padding: 0; max-width: 100%; margin: 0; background: #f8f8f8; border: 1px solid #ccc; padding: 0.375em 0.625em; font-size: 0.86em; .rounded(.25em); } pre.code-block { overflow-x: auto; } diff --git a/oauth.go b/oauth.go index 4758e0f..eb47c91 100644 --- a/oauth.go +++ b/oauth.go @@ -1,244 +1,286 @@ package writefreely import ( "context" "encoding/json" "fmt" "github.com/gorilla/mux" "github.com/gorilla/sessions" "github.com/writeas/impart" - "github.com/writeas/nerds/store" - "github.com/writeas/web-core/auth" "github.com/writeas/web-core/log" "github.com/writeas/writefreely/config" "io" "io/ioutil" "net/http" + "net/url" + "strings" "time" ) // TokenResponse contains data returned when a token is created either // through a code exchange or using a refresh token. type TokenResponse struct { AccessToken string `json:"access_token"` ExpiresIn int `json:"expires_in"` RefreshToken string `json:"refresh_token"` TokenType string `json:"token_type"` Error string `json:"error"` } // InspectResponse contains data returned when an access token is inspected. type InspectResponse struct { ClientID string `json:"client_id"` UserID string `json:"user_id"` ExpiresAt time.Time `json:"expires_at"` Username string `json:"username"` DisplayName string `json:"-"` Email string `json:"email"` Error string `json:"error"` } // tokenRequestMaxLen is the most bytes that we'll read from the /oauth/token // endpoint. One megabyte is plenty. const tokenRequestMaxLen = 1000000 // infoRequestMaxLen is the most bytes that we'll read from the // /oauth/inspect endpoint. const infoRequestMaxLen = 1000000 // OAuthDatastoreProvider provides a minimal interface of data store, config, // and session store for use with the oauth handlers. type OAuthDatastoreProvider interface { DB() OAuthDatastore Config() *config.Config SessionStore() sessions.Store } // OAuthDatastore provides a minimal interface of data store methods used in // oauth functionality. type OAuthDatastore interface { GetIDForRemoteUser(context.Context, string, string, string) (int64, error) RecordRemoteUserID(context.Context, int64, string, string, string, string) error ValidateOAuthState(context.Context, string) (string, string, error) GenerateOAuthState(context.Context, string, string) (string, error) CreateUser(*config.Config, *User, string) error GetUserByID(int64) (*User, error) } type HttpClient interface { Do(req *http.Request) (*http.Response, error) } type oauthClient interface { GetProvider() string GetClientID() string + GetCallbackLocation() string buildLoginURL(state string) (string, error) exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error) inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error) } +type callbackProxyClient struct { + server string + callbackLocation string + httpClient HttpClient +} + type oauthHandler struct { - Config *config.Config - DB OAuthDatastore - Store sessions.Store - EmailKey []byte - oauthClient oauthClient + Config *config.Config + DB OAuthDatastore + Store sessions.Store + EmailKey []byte + oauthClient oauthClient + callbackProxy *callbackProxyClient } func (h oauthHandler) viewOauthInit(app *App, w http.ResponseWriter, r *http.Request) error { ctx := r.Context() state, err := h.DB.GenerateOAuthState(ctx, h.oauthClient.GetProvider(), h.oauthClient.GetClientID()) if err != nil { return impart.HTTPError{http.StatusInternalServerError, "could not prepare oauth redirect url"} } + + if h.callbackProxy != nil { + if err := h.callbackProxy.register(ctx, state); err != nil { + return impart.HTTPError{http.StatusInternalServerError, "could not register state server"} + } + } + location, err := h.oauthClient.buildLoginURL(state) if err != nil { return impart.HTTPError{http.StatusInternalServerError, "could not prepare oauth redirect url"} } return impart.HTTPError{http.StatusTemporaryRedirect, location} } func configureSlackOauth(parentHandler *Handler, r *mux.Router, app *App) { if app.Config().SlackOauth.ClientID != "" { + callbackLocation := app.Config().App.Host + "/oauth/callback" + + var stateRegisterClient *callbackProxyClient = nil + if app.Config().SlackOauth.CallbackProxyAPI != "" { + stateRegisterClient = &callbackProxyClient{ + server: app.Config().SlackOauth.CallbackProxyAPI, + callbackLocation: app.Config().App.Host + "/oauth/callback", + httpClient: config.DefaultHTTPClient(), + } + callbackLocation = app.Config().SlackOauth.CallbackProxy + } oauthClient := slackOauthClient{ ClientID: app.Config().SlackOauth.ClientID, ClientSecret: app.Config().SlackOauth.ClientSecret, TeamID: app.Config().SlackOauth.TeamID, - CallbackLocation: app.Config().App.Host + "/oauth/callback", HttpClient: config.DefaultHTTPClient(), + CallbackLocation: callbackLocation, } - configureOauthRoutes(parentHandler, r, app, oauthClient) + configureOauthRoutes(parentHandler, r, app, oauthClient, stateRegisterClient) } } func configureWriteAsOauth(parentHandler *Handler, r *mux.Router, app *App) { if app.Config().WriteAsOauth.ClientID != "" { + callbackLocation := app.Config().App.Host + "/oauth/callback" + + var callbackProxy *callbackProxyClient = nil + if app.Config().WriteAsOauth.CallbackProxy != "" { + callbackProxy = &callbackProxyClient{ + server: app.Config().WriteAsOauth.CallbackProxyAPI, + callbackLocation: app.Config().App.Host + "/oauth/callback", + httpClient: config.DefaultHTTPClient(), + } + callbackLocation = app.Config().SlackOauth.CallbackProxy + } + oauthClient := writeAsOauthClient{ ClientID: app.Config().WriteAsOauth.ClientID, ClientSecret: app.Config().WriteAsOauth.ClientSecret, ExchangeLocation: config.OrDefaultString(app.Config().WriteAsOauth.TokenLocation, writeAsExchangeLocation), InspectLocation: config.OrDefaultString(app.Config().WriteAsOauth.InspectLocation, writeAsIdentityLocation), AuthLocation: config.OrDefaultString(app.Config().WriteAsOauth.AuthLocation, writeAsAuthLocation), HttpClient: config.DefaultHTTPClient(), - CallbackLocation: app.Config().App.Host + "/oauth/callback", + CallbackLocation: callbackLocation, } - configureOauthRoutes(parentHandler, r, app, oauthClient) + configureOauthRoutes(parentHandler, r, app, oauthClient, callbackProxy) } } -func configureOauthRoutes(parentHandler *Handler, r *mux.Router, app *App, oauthClient oauthClient) { +func configureOauthRoutes(parentHandler *Handler, r *mux.Router, app *App, oauthClient oauthClient, callbackProxy *callbackProxyClient) { handler := &oauthHandler{ - Config: app.Config(), - DB: app.DB(), - Store: app.SessionStore(), - oauthClient: oauthClient, - EmailKey: app.keys.EmailKey, + Config: app.Config(), + DB: app.DB(), + Store: app.SessionStore(), + oauthClient: oauthClient, + EmailKey: app.keys.EmailKey, + callbackProxy: callbackProxy, } r.HandleFunc("/oauth/"+oauthClient.GetProvider(), parentHandler.OAuth(handler.viewOauthInit)).Methods("GET") r.HandleFunc("/oauth/callback", parentHandler.OAuth(handler.viewOauthCallback)).Methods("GET") + r.HandleFunc("/oauth/signup", parentHandler.OAuth(handler.viewOauthSignup)).Methods("POST") } func (h oauthHandler) viewOauthCallback(app *App, w http.ResponseWriter, r *http.Request) error { ctx := r.Context() code := r.FormValue("code") state := r.FormValue("state") provider, clientID, err := h.DB.ValidateOAuthState(ctx, state) if err != nil { log.Error("Unable to ValidateOAuthState: %s", err) return impart.HTTPError{http.StatusInternalServerError, err.Error()} } tokenResponse, err := h.oauthClient.exchangeOauthCode(ctx, code) if err != nil { log.Error("Unable to exchangeOauthCode: %s", err) return impart.HTTPError{http.StatusInternalServerError, err.Error()} } // Now that we have the access token, let's use it real quick to make sur // it really really works. tokenInfo, err := h.oauthClient.inspectOauthAccessToken(ctx, tokenResponse.AccessToken) if err != nil { log.Error("Unable to inspectOauthAccessToken: %s", err) return impart.HTTPError{http.StatusInternalServerError, err.Error()} } localUserID, err := h.DB.GetIDForRemoteUser(ctx, tokenInfo.UserID, provider, clientID) if err != nil { log.Error("Unable to GetIDForRemoteUser: %s", err) return impart.HTTPError{http.StatusInternalServerError, err.Error()} } - if localUserID == -1 { - // We don't have, nor do we want, the password from the origin, so we - //create a random string. If the user needs to set a password, they - //can do so through the settings page or through the password reset - //flow. - randPass := store.Generate62RandomString(14) - hashedPass, err := auth.HashPass([]byte(randPass)) - if err != nil { - return impart.HTTPError{http.StatusInternalServerError, "unable to create password hash"} - } - newUser := &User{ - Username: tokenInfo.Username, - HashedPass: hashedPass, - HasPass: true, - Email: prepareUserEmail(tokenInfo.Email, h.EmailKey), - Created: time.Now().Truncate(time.Second).UTC(), - } - displayName := tokenInfo.DisplayName - if len(displayName) == 0 { - displayName = tokenInfo.Username - } - - err = h.DB.CreateUser(h.Config, newUser, displayName) + if localUserID != -1 { + user, err := h.DB.GetUserByID(localUserID) if err != nil { + log.Error("Unable to GetUserByID %d: %s", localUserID, err) return impart.HTTPError{http.StatusInternalServerError, err.Error()} } - - err = h.DB.RecordRemoteUserID(ctx, newUser.ID, tokenInfo.UserID, provider, clientID, tokenResponse.AccessToken) - if err != nil { - return impart.HTTPError{http.StatusInternalServerError, err.Error()} - } - - if err := loginOrFail(h.Store, w, r, newUser); err != nil { + if err = loginOrFail(h.Store, w, r, user); err != nil { + log.Error("Unable to loginOrFail %d: %s", localUserID, err) return impart.HTTPError{http.StatusInternalServerError, err.Error()} } return nil } - user, err := h.DB.GetUserByID(localUserID) + tp := &oauthSignupPageParams{ + AccessToken: tokenResponse.AccessToken, + TokenUsername: tokenInfo.Username, + TokenAlias: tokenInfo.DisplayName, + TokenEmail: tokenInfo.Email, + TokenRemoteUser: tokenInfo.UserID, + Provider: provider, + ClientID: clientID, + } + tp.TokenHash = tp.HashTokenParams(h.Config.Server.HashSeed) + + return h.showOauthSignupPage(app, w, r, tp, nil) +} + +func (r *callbackProxyClient) register(ctx context.Context, state string) error { + form := url.Values{} + form.Add("state", state) + form.Add("location", r.callbackLocation) + req, err := http.NewRequestWithContext(ctx, "POST", r.server, strings.NewReader(form.Encode())) + if err != nil { + return err + } + req.Header.Set("User-Agent", "writefreely") + req.Header.Set("Accept", "application/json") + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + resp, err := r.httpClient.Do(req) if err != nil { - return impart.HTTPError{http.StatusInternalServerError, err.Error()} + return err } - if err = loginOrFail(h.Store, w, r, user); err != nil { - return impart.HTTPError{http.StatusInternalServerError, err.Error()} + if resp.StatusCode != http.StatusCreated { + return fmt.Errorf("unable register state location: %d", resp.StatusCode) } + return nil } func limitedJsonUnmarshal(body io.ReadCloser, n int, thing interface{}) error { lr := io.LimitReader(body, int64(n+1)) data, err := ioutil.ReadAll(lr) if err != nil { return err } if len(data) == n+1 { return fmt.Errorf("content larger than max read allowance: %d", n) } return json.Unmarshal(data, thing) } func loginOrFail(store sessions.Store, w http.ResponseWriter, r *http.Request, user *User) error { // An error may be returned, but a valid session should always be returned. session, _ := store.Get(r, cookieName) session.Values[cookieUserVal] = user.Cookie() if err := session.Save(r, w); err != nil { fmt.Println("error saving session", err) return err } http.Redirect(w, r, "/", http.StatusTemporaryRedirect) return nil } diff --git a/oauth_signup.go b/oauth_signup.go new file mode 100644 index 0000000..cf90af6 --- /dev/null +++ b/oauth_signup.go @@ -0,0 +1,206 @@ +package writefreely + +import ( + "crypto/sha256" + "encoding/hex" + "fmt" + "github.com/writeas/impart" + "github.com/writeas/web-core/auth" + "github.com/writeas/web-core/log" + "github.com/writeas/writefreely/page" + "html/template" + "net/http" + "strings" + "time" +) + +type viewOauthSignupVars struct { + page.StaticPage + To string + Message template.HTML + Flashes []template.HTML + + AccessToken string + TokenUsername string + TokenAlias string + TokenEmail string + TokenRemoteUser string + Provider string + ClientID string + TokenHash string + + Username string + Alias string + Email string +} + +const ( + oauthParamAccessToken = "access_token" + oauthParamTokenUsername = "token_username" + oauthParamTokenAlias = "token_alias" + oauthParamTokenEmail = "token_email" + oauthParamTokenRemoteUserID = "token_remote_user" + oauthParamClientID = "client_id" + oauthParamProvider = "provider" + oauthParamHash = "signature" + oauthParamUsername = "username" + oauthParamAlias = "alias" + oauthParamEmail = "email" + oauthParamPassword = "password" +) + +type oauthSignupPageParams struct { + AccessToken string + TokenUsername string + TokenAlias string + TokenEmail string + TokenRemoteUser string + ClientID string + Provider string + TokenHash string +} + +func (p oauthSignupPageParams) HashTokenParams(key string) string { + hasher := sha256.New() + hasher.Write([]byte(key)) + hasher.Write([]byte(p.AccessToken)) + hasher.Write([]byte(p.TokenUsername)) + hasher.Write([]byte(p.TokenAlias)) + hasher.Write([]byte(p.TokenEmail)) + hasher.Write([]byte(p.TokenRemoteUser)) + hasher.Write([]byte(p.ClientID)) + hasher.Write([]byte(p.Provider)) + return hex.EncodeToString(hasher.Sum(nil)) +} + +func (h oauthHandler) viewOauthSignup(app *App, w http.ResponseWriter, r *http.Request) error { + tp := &oauthSignupPageParams{ + AccessToken: r.FormValue(oauthParamAccessToken), + TokenUsername: r.FormValue(oauthParamTokenUsername), + TokenAlias: r.FormValue(oauthParamTokenAlias), + TokenEmail: r.FormValue(oauthParamTokenEmail), + TokenRemoteUser: r.FormValue(oauthParamTokenRemoteUserID), + ClientID: r.FormValue(oauthParamClientID), + Provider: r.FormValue(oauthParamProvider), + } + if tp.HashTokenParams(h.Config.Server.HashSeed) != r.FormValue(oauthParamHash) { + return impart.HTTPError{Status: http.StatusBadRequest, Message: "Request has been tampered with."} + } + tp.TokenHash = tp.HashTokenParams(h.Config.Server.HashSeed) + if err := h.validateOauthSignup(r); err != nil { + return h.showOauthSignupPage(app, w, r, tp, err) + } + + hashedPass, err := auth.HashPass([]byte(r.FormValue(oauthParamPassword))) + if err != nil { + return h.showOauthSignupPage(app, w, r, tp, fmt.Errorf("unable to hash password")) + } + newUser := &User{ + Username: r.FormValue(oauthParamUsername), + HashedPass: hashedPass, + HasPass: true, + Email: prepareUserEmail(r.FormValue(oauthParamEmail), h.EmailKey), + Created: time.Now().Truncate(time.Second).UTC(), + } + displayName := r.FormValue(oauthParamAlias) + if len(displayName) == 0 { + displayName = r.FormValue(oauthParamUsername) + } + + err = h.DB.CreateUser(h.Config, newUser, displayName) + if err != nil { + return h.showOauthSignupPage(app, w, r, tp, err) + } + + err = h.DB.RecordRemoteUserID(r.Context(), newUser.ID, r.FormValue(oauthParamTokenRemoteUserID), r.FormValue(oauthParamProvider), r.FormValue(oauthParamClientID), r.FormValue(oauthParamAccessToken)) + if err != nil { + return h.showOauthSignupPage(app, w, r, tp, err) + } + + if err := loginOrFail(h.Store, w, r, newUser); err != nil { + return h.showOauthSignupPage(app, w, r, tp, err) + } + return nil +} + +func (h oauthHandler) validateOauthSignup(r *http.Request) error { + username := r.FormValue(oauthParamUsername) + if len(username) < h.Config.App.MinUsernameLen { + return impart.HTTPError{Status: http.StatusBadRequest, Message: "Username is too short."} + } + if len(username) > 100 { + return impart.HTTPError{Status: http.StatusBadRequest, Message: "Username is too long."} + } + alias := r.FormValue(oauthParamAlias) + if len(alias) == 0 { + return impart.HTTPError{Status: http.StatusBadRequest, Message: "Alias is too short."} + } + password := r.FormValue("password") + if len(password) == 0 { + return impart.HTTPError{Status: http.StatusBadRequest, Message: "Password is too short."} + } + email := r.FormValue(oauthParamEmail) + if len(email) > 0 { + parts := strings.Split(email, "@") + if len(parts) != 2 || (len(parts[0]) < 1 || len(parts[1]) < 1) { + return impart.HTTPError{Status: http.StatusBadRequest, Message: "Invalid email address"} + } + } + return nil +} + +func (h oauthHandler) showOauthSignupPage(app *App, w http.ResponseWriter, r *http.Request, tp *oauthSignupPageParams, errMsg error) error { + username := tp.TokenUsername + alias := tp.TokenAlias + email := tp.TokenEmail + + session, err := app.sessionStore.Get(r, cookieName) + if err != nil { + // Ignore this + log.Error("Unable to get session; ignoring: %v", err) + } + + if tmpValue := r.FormValue(oauthParamUsername); len(tmpValue) > 0 { + username = tmpValue + } + if tmpValue := r.FormValue(oauthParamAlias); len(tmpValue) > 0 { + alias = tmpValue + } + if tmpValue := r.FormValue(oauthParamEmail); len(tmpValue) > 0 { + email = tmpValue + } + + p := &viewOauthSignupVars{ + StaticPage: pageForReq(app, r), + To: r.FormValue("to"), + Flashes: []template.HTML{}, + + AccessToken: tp.AccessToken, + TokenUsername: tp.TokenUsername, + TokenAlias: tp.TokenAlias, + TokenEmail: tp.TokenEmail, + TokenRemoteUser: tp.TokenRemoteUser, + Provider: tp.Provider, + ClientID: tp.ClientID, + TokenHash: tp.TokenHash, + + Username: username, + Alias: alias, + Email: email, + } + + // Display any error messages + flashes, _ := getSessionFlashes(app, w, r, session) + for _, flash := range flashes { + p.Flashes = append(p.Flashes, template.HTML(flash)) + } + if errMsg != nil { + p.Flashes = append(p.Flashes, template.HTML(errMsg.Error())) + } + err = pages["signup-oauth.tmpl"].ExecuteTemplate(w, "base", p) + if err != nil { + log.Error("Unable to render signup-oauth: %v", err) + return err + } + return nil +} diff --git a/oauth_slack.go b/oauth_slack.go index 066aa18..8cf4992 100644 --- a/oauth_slack.go +++ b/oauth_slack.go @@ -1,164 +1,170 @@ package writefreely import ( "context" "errors" + "fmt" + "github.com/writeas/nerds/store" "github.com/writeas/slug" "net/http" "net/url" "strings" ) type slackOauthClient struct { ClientID string ClientSecret string TeamID string CallbackLocation string HttpClient HttpClient } type slackExchangeResponse struct { OK bool `json:"ok"` AccessToken string `json:"access_token"` Scope string `json:"scope"` TeamName string `json:"team_name"` TeamID string `json:"team_id"` Error string `json:"error"` } type slackIdentity struct { Name string `json:"name"` ID string `json:"id"` Email string `json:"email"` } type slackTeam struct { Name string `json:"name"` ID string `json:"id"` } type slackUserIdentityResponse struct { OK bool `json:"ok"` User slackIdentity `json:"user"` Team slackTeam `json:"team"` Error string `json:"error"` } const ( slackAuthLocation = "https://slack.com/oauth/authorize" slackExchangeLocation = "https://slack.com/api/oauth.access" slackIdentityLocation = "https://slack.com/api/users.identity" ) var _ oauthClient = slackOauthClient{} func (c slackOauthClient) GetProvider() string { return "slack" } func (c slackOauthClient) GetClientID() string { return c.ClientID } +func (c slackOauthClient) GetCallbackLocation() string { + return c.CallbackLocation +} + func (c slackOauthClient) buildLoginURL(state string) (string, error) { u, err := url.Parse(slackAuthLocation) if err != nil { return "", err } q := u.Query() q.Set("client_id", c.ClientID) q.Set("scope", "identity.basic identity.email identity.team") q.Set("redirect_uri", c.CallbackLocation) q.Set("state", state) // If this param is not set, the user can select which team they // authenticate through and then we'd have to match the configured team // against the profile get. That is extra work in the post-auth phase // that we don't want to do. q.Set("team", c.TeamID) // The Slack OAuth docs don't explicitly list this one, but it is part of // the spec, so we include it anyway. q.Set("response_type", "code") u.RawQuery = q.Encode() return u.String(), nil } func (c slackOauthClient) exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error) { form := url.Values{} // The oauth.access documentation doesn't explicitly mention this // parameter, but it is part of the spec, so we include it anyway. // https://api.slack.com/methods/oauth.access form.Add("grant_type", "authorization_code") form.Add("redirect_uri", c.CallbackLocation) form.Add("code", code) req, err := http.NewRequest("POST", slackExchangeLocation, strings.NewReader(form.Encode())) if err != nil { return nil, err } req.WithContext(ctx) req.Header.Set("User-Agent", "writefreely") req.Header.Set("Accept", "application/json") req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.SetBasicAuth(c.ClientID, c.ClientSecret) resp, err := c.HttpClient.Do(req) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, errors.New("unable to exchange code for access token") } var tokenResponse slackExchangeResponse if err := limitedJsonUnmarshal(resp.Body, tokenRequestMaxLen, &tokenResponse); err != nil { return nil, err } if !tokenResponse.OK { return nil, errors.New(tokenResponse.Error) } return tokenResponse.TokenResponse(), nil } func (c slackOauthClient) inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error) { req, err := http.NewRequest("GET", slackIdentityLocation, nil) if err != nil { return nil, err } req.WithContext(ctx) req.Header.Set("User-Agent", "writefreely") req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Bearer "+accessToken) resp, err := c.HttpClient.Do(req) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, errors.New("unable to inspect access token") } var inspectResponse slackUserIdentityResponse if err := limitedJsonUnmarshal(resp.Body, infoRequestMaxLen, &inspectResponse); err != nil { return nil, err } if !inspectResponse.OK { return nil, errors.New(inspectResponse.Error) } return inspectResponse.InspectResponse(), nil } func (resp slackUserIdentityResponse) InspectResponse() *InspectResponse { return &InspectResponse{ UserID: resp.User.ID, - Username: slug.Make(resp.User.Name), + Username: fmt.Sprintf("%s-%s", slug.Make(resp.User.Name), store.Generate62RandomString(5)), DisplayName: resp.User.Name, Email: resp.User.Email, } } func (resp slackExchangeResponse) TokenResponse() *TokenResponse { return &TokenResponse{ AccessToken: resp.AccessToken, } } diff --git a/oauth_writeas.go b/oauth_writeas.go index eb12f64..6251a16 100644 --- a/oauth_writeas.go +++ b/oauth_writeas.go @@ -1,110 +1,114 @@ package writefreely import ( "context" "errors" "net/http" "net/url" "strings" ) type writeAsOauthClient struct { ClientID string ClientSecret string AuthLocation string ExchangeLocation string InspectLocation string CallbackLocation string HttpClient HttpClient } var _ oauthClient = writeAsOauthClient{} const ( writeAsAuthLocation = "https://write.as/oauth/login" writeAsExchangeLocation = "https://write.as/oauth/token" writeAsIdentityLocation = "https://write.as/oauth/inspect" ) func (c writeAsOauthClient) GetProvider() string { return "write.as" } func (c writeAsOauthClient) GetClientID() string { return c.ClientID } +func (c writeAsOauthClient) GetCallbackLocation() string { + return c.CallbackLocation +} + func (c writeAsOauthClient) buildLoginURL(state string) (string, error) { u, err := url.Parse(c.AuthLocation) if err != nil { return "", err } q := u.Query() q.Set("client_id", c.ClientID) q.Set("redirect_uri", c.CallbackLocation) q.Set("response_type", "code") q.Set("state", state) u.RawQuery = q.Encode() return u.String(), nil } func (c writeAsOauthClient) exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error) { form := url.Values{} form.Add("grant_type", "authorization_code") form.Add("redirect_uri", c.CallbackLocation) form.Add("code", code) req, err := http.NewRequest("POST", c.ExchangeLocation, strings.NewReader(form.Encode())) if err != nil { return nil, err } req.WithContext(ctx) req.Header.Set("User-Agent", "writefreely") req.Header.Set("Accept", "application/json") req.Header.Set("Content-Type", "application/x-www-form-urlencoded") req.SetBasicAuth(c.ClientID, c.ClientSecret) resp, err := c.HttpClient.Do(req) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, errors.New("unable to exchange code for access token") } var tokenResponse TokenResponse if err := limitedJsonUnmarshal(resp.Body, tokenRequestMaxLen, &tokenResponse); err != nil { return nil, err } if tokenResponse.Error != "" { return nil, errors.New(tokenResponse.Error) } return &tokenResponse, nil } func (c writeAsOauthClient) inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error) { req, err := http.NewRequest("GET", c.InspectLocation, nil) if err != nil { return nil, err } req.WithContext(ctx) req.Header.Set("User-Agent", "writefreely") req.Header.Set("Accept", "application/json") req.Header.Set("Authorization", "Bearer "+accessToken) resp, err := c.HttpClient.Do(req) if err != nil { return nil, err } if resp.StatusCode != http.StatusOK { return nil, errors.New("unable to inspect access token") } var inspectResponse InspectResponse if err := limitedJsonUnmarshal(resp.Body, infoRequestMaxLen, &inspectResponse); err != nil { return nil, err } if inspectResponse.Error != "" { return nil, errors.New(inspectResponse.Error) } return &inspectResponse, nil } diff --git a/pages/login.tmpl b/pages/login.tmpl index 1c8e862..345b171 100644 --- a/pages/login.tmpl +++ b/pages/login.tmpl @@ -1,30 +1,77 @@ {{define "head"}}Log in — {{.SiteName}} - + {{end}} {{define "content"}}

Log in to {{.SiteName}}

{{if .Flashes}}{{end}} + {{ if or .OauthSlack .OauthWriteAs }} +
+ {{ if .OauthSlack }} + Sign in with Slack + {{ end }} + {{ if .OauthWriteAs }} + Sign in with Write.as + {{ end }} +
+ +
+

or

+
+
+ {{ end }} +


{{if .To}}{{end}}
{{if and (not .SingleUser) .OpenRegistration}}

{{if .Message}}{{.Message}}{{else}}No account yet? Sign up to start a blog.{{end}}

{{end}} {{end}} diff --git a/pages/signup-oauth.tmpl b/pages/signup-oauth.tmpl new file mode 100644 index 0000000..34081cf --- /dev/null +++ b/pages/signup-oauth.tmpl @@ -0,0 +1,118 @@ +{{define "head"}}Log in — {{.SiteName}} + + + + +{{end}} +{{define "content"}} +
+

Log in to {{.SiteName}}

+ + {{if .Flashes}}{{end}} + +
+
+ + + + + + + + + +
+ + + + +
+ +
+
+
+
+ + +{{end}} diff --git a/static/img/sign_in_with_slack.png b/static/img/sign_in_with_slack.png new file mode 100644 index 0000000..66e4298 Binary files /dev/null and b/static/img/sign_in_with_slack.png differ diff --git a/static/img/sign_in_with_slack@2x.png b/static/img/sign_in_with_slack@2x.png new file mode 100644 index 0000000..14a674a Binary files /dev/null and b/static/img/sign_in_with_slack@2x.png differ