2019-12-19 16:48:04 +00:00
|
|
|
package writefreely
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
"encoding/json"
|
2019-12-23 19:30:32 +00:00
|
|
|
"fmt"
|
2019-12-27 18:40:11 +00:00
|
|
|
"github.com/gorilla/mux"
|
2019-12-19 16:48:04 +00:00
|
|
|
"github.com/gorilla/sessions"
|
|
|
|
"github.com/guregu/null/zero"
|
2019-12-27 18:35:48 +00:00
|
|
|
"github.com/writeas/nerds/store"
|
2019-12-19 16:48:04 +00:00
|
|
|
"github.com/writeas/web-core/auth"
|
|
|
|
"github.com/writeas/writefreely/config"
|
|
|
|
"io"
|
|
|
|
"io/ioutil"
|
|
|
|
"net/http"
|
|
|
|
"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"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// InspectResponse contains data returned when an access token is inspected.
|
|
|
|
type InspectResponse struct {
|
|
|
|
ClientID string `json:"client_id"`
|
2019-12-28 20:15:47 +00:00
|
|
|
UserID string `json:"user_id"`
|
2019-12-19 16:48:04 +00:00
|
|
|
ExpiresAt time.Time `json:"expires_at"`
|
|
|
|
Username string `json:"username"`
|
|
|
|
Email string `json:"email"`
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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 {
|
2019-12-30 18:32:06 +00:00
|
|
|
GetIDForRemoteUser(context.Context, string, string, string) (int64, error)
|
|
|
|
RecordRemoteUserID(context.Context, int64, string, string, string, string) error
|
2019-12-28 20:15:47 +00:00
|
|
|
ValidateOAuthState(context.Context, string) (string, string, error)
|
2019-12-27 18:40:11 +00:00
|
|
|
GenerateOAuthState(context.Context, string, string) (string, error)
|
|
|
|
|
|
|
|
CreateUser(*config.Config, *User, string) error
|
2019-12-19 16:48:04 +00:00
|
|
|
GetUserForAuthByID(int64) (*User, error)
|
|
|
|
}
|
|
|
|
|
|
|
|
type HttpClient interface {
|
|
|
|
Do(req *http.Request) (*http.Response, error)
|
|
|
|
}
|
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
type oauthClient interface {
|
|
|
|
GetProvider() string
|
|
|
|
GetClientID() string
|
|
|
|
buildLoginURL(state string) (string, error)
|
|
|
|
exchangeOauthCode(ctx context.Context, code string) (*TokenResponse, error)
|
|
|
|
inspectOauthAccessToken(ctx context.Context, accessToken string) (*InspectResponse, error)
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
type oauthHandler struct {
|
|
|
|
Config *config.Config
|
|
|
|
DB OAuthDatastore
|
|
|
|
Store sessions.Store
|
|
|
|
oauthClient oauthClient
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
func (h oauthHandler) viewOauthInit(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
|
|
|
state, err := h.DB.GenerateOAuthState(ctx, h.oauthClient.GetProvider(), h.oauthClient.GetClientID())
|
2019-12-19 16:48:04 +00:00
|
|
|
if err != nil {
|
2019-12-23 19:30:32 +00:00
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, "could not prepare oauth redirect url")
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
2019-12-28 20:15:47 +00:00
|
|
|
location, err := h.oauthClient.buildLoginURL(state)
|
2019-12-19 16:48:04 +00:00
|
|
|
if err != nil {
|
2019-12-27 18:40:11 +00:00
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, "could not prepare oauth redirect url")
|
2019-12-23 19:30:32 +00:00
|
|
|
return
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
2019-12-27 18:40:11 +00:00
|
|
|
http.Redirect(w, r, location, http.StatusTemporaryRedirect)
|
|
|
|
}
|
2019-12-19 16:48:04 +00:00
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
func configureSlackOauth(r *mux.Router, app *App) {
|
|
|
|
if app.Config().SlackOauth.ClientID != "" {
|
|
|
|
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: &http.Client{Timeout: 10 * time.Second},
|
2019-12-27 18:40:11 +00:00
|
|
|
}
|
2019-12-28 20:15:47 +00:00
|
|
|
configureOauthRoutes(r, app, oauthClient)
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
2019-12-28 20:15:47 +00:00
|
|
|
}
|
2019-12-19 16:48:04 +00:00
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
func configureWriteAsOauth(r *mux.Router, app *App) {
|
|
|
|
if app.Config().WriteAsOauth.ClientID != "" {
|
|
|
|
oauthClient := writeAsOauthClient{
|
|
|
|
ClientID: app.Config().WriteAsOauth.ClientID,
|
|
|
|
ClientSecret: app.Config().WriteAsOauth.ClientSecret,
|
|
|
|
ExchangeLocation: app.Config().WriteAsOauth.TokenLocation,
|
|
|
|
InspectLocation: app.Config().WriteAsOauth.InspectLocation,
|
|
|
|
AuthLocation: app.Config().WriteAsOauth.AuthLocation,
|
|
|
|
HttpClient: &http.Client{Timeout: 10 * time.Second},
|
|
|
|
CallbackLocation: app.Config().App.Host + "/oauth/callback",
|
|
|
|
}
|
|
|
|
configureOauthRoutes(r, app, oauthClient)
|
|
|
|
}
|
2019-12-27 18:40:11 +00:00
|
|
|
}
|
2019-12-19 16:48:04 +00:00
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
func configureOauthRoutes(r *mux.Router, app *App, oauthClient oauthClient) {
|
|
|
|
handler := &oauthHandler{
|
|
|
|
Config: app.Config(),
|
|
|
|
DB: app.DB(),
|
|
|
|
Store: app.SessionStore(),
|
|
|
|
oauthClient: oauthClient,
|
|
|
|
}
|
|
|
|
r.HandleFunc("/oauth/"+oauthClient.GetProvider(), handler.viewOauthInit).Methods("GET")
|
|
|
|
r.HandleFunc("/oauth/callback", handler.viewOauthCallback).Methods("GET")
|
2019-12-27 18:40:11 +00:00
|
|
|
}
|
2019-12-19 16:48:04 +00:00
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
func (h oauthHandler) viewOauthCallback(w http.ResponseWriter, r *http.Request) {
|
|
|
|
ctx := r.Context()
|
2019-12-23 19:30:32 +00:00
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
code := r.FormValue("code")
|
|
|
|
state := r.FormValue("state")
|
2019-12-27 18:40:11 +00:00
|
|
|
|
2019-12-30 18:32:06 +00:00
|
|
|
provider, clientID, err := h.DB.ValidateOAuthState(ctx, state)
|
2019-12-28 20:15:47 +00:00
|
|
|
if err != nil {
|
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, err.Error())
|
|
|
|
return
|
|
|
|
}
|
2019-12-19 16:48:04 +00:00
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
tokenResponse, err := h.oauthClient.exchangeOauthCode(ctx, code)
|
|
|
|
if err != nil {
|
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// 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 {
|
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, err.Error())
|
|
|
|
return
|
|
|
|
}
|
2019-12-19 16:48:04 +00:00
|
|
|
|
2019-12-30 18:32:06 +00:00
|
|
|
localUserID, err := h.DB.GetIDForRemoteUser(ctx, tokenInfo.UserID, provider, clientID)
|
2019-12-28 20:15:47 +00:00
|
|
|
if err != nil {
|
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
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))
|
2019-12-19 16:48:04 +00:00
|
|
|
if err != nil {
|
2019-12-28 20:15:47 +00:00
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, "unable to create password hash")
|
2019-12-23 19:30:32 +00:00
|
|
|
return
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
2019-12-28 20:15:47 +00:00
|
|
|
newUser := &User{
|
|
|
|
Username: tokenInfo.Username,
|
|
|
|
HashedPass: hashedPass,
|
|
|
|
HasPass: true,
|
|
|
|
Email: zero.NewString(tokenInfo.Email, tokenInfo.Email != ""),
|
|
|
|
Created: time.Now().Truncate(time.Second).UTC(),
|
|
|
|
}
|
2019-12-19 16:48:04 +00:00
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
err = h.DB.CreateUser(h.Config, newUser, newUser.Username)
|
2019-12-27 18:40:11 +00:00
|
|
|
if err != nil {
|
2019-12-23 19:30:32 +00:00
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, err.Error())
|
2019-12-27 18:40:11 +00:00
|
|
|
return
|
2019-12-23 19:30:32 +00:00
|
|
|
}
|
2019-12-19 16:48:04 +00:00
|
|
|
|
2019-12-30 18:32:06 +00:00
|
|
|
err = h.DB.RecordRemoteUserID(ctx, newUser.ID, tokenInfo.UserID, provider, clientID, tokenResponse.AccessToken)
|
2019-12-27 18:40:11 +00:00
|
|
|
if err != nil {
|
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, err.Error())
|
|
|
|
return
|
|
|
|
}
|
2019-12-28 20:15:47 +00:00
|
|
|
|
|
|
|
if err := loginOrFail(h.Store, w, r, newUser); err != nil {
|
2019-12-27 18:40:11 +00:00
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, err.Error())
|
|
|
|
}
|
2019-12-28 20:15:47 +00:00
|
|
|
return
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
user, err := h.DB.GetUserForAuthByID(localUserID)
|
2019-12-19 16:48:04 +00:00
|
|
|
if err != nil {
|
2019-12-28 20:15:47 +00:00
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, err.Error())
|
|
|
|
return
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
2019-12-28 20:15:47 +00:00
|
|
|
if err = loginOrFail(h.Store, w, r, user); err != nil {
|
|
|
|
failOAuthRequest(w, http.StatusInternalServerError, err.Error())
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-28 20:15:47 +00:00
|
|
|
func limitedJsonUnmarshal(body io.ReadCloser, n int, thing interface{}) error {
|
|
|
|
lr := io.LimitReader(body, int64(n+1))
|
|
|
|
data, err := ioutil.ReadAll(lr)
|
2019-12-19 16:48:04 +00:00
|
|
|
if err != nil {
|
2019-12-28 20:15:47 +00:00
|
|
|
return err
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
2019-12-28 20:15:47 +00:00
|
|
|
if len(data) == n+1 {
|
|
|
|
return fmt.Errorf("content larger than max read allowance: %d", n)
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
2019-12-28 20:15:47 +00:00
|
|
|
return json.Unmarshal(data, thing)
|
2019-12-19 16:48:04 +00:00
|
|
|
}
|
|
|
|
|
2019-12-23 19:30:32 +00:00
|
|
|
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)
|
2019-12-19 16:48:04 +00:00
|
|
|
session.Values[cookieUserVal] = user.Cookie()
|
2019-12-23 19:30:32 +00:00
|
|
|
if err := session.Save(r, w); err != nil {
|
|
|
|
fmt.Println("error saving session", err)
|
2019-12-19 16:48:04 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
|
|
|
|
return nil
|
|
|
|
}
|
2019-12-23 19:30:32 +00:00
|
|
|
|
|
|
|
// failOAuthRequest is an HTTP handler helper that formats returned error
|
|
|
|
// messages.
|
|
|
|
func failOAuthRequest(w http.ResponseWriter, statusCode int, message string) {
|
|
|
|
w.Header().Set("Content-Type", "application/json")
|
|
|
|
w.WriteHeader(statusCode)
|
|
|
|
err := json.NewEncoder(w).Encode(map[string]interface{}{
|
|
|
|
"error": message,
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|