Login: Add Token based authentication

Signed-off-by: Anant Prakash <anantprakashjsr@gmail.com>
This commit is contained in:
Anant Prakash 2018-03-03 21:34:30 +00:00
parent c9add39768
commit 00d8373dd5
4 changed files with 238 additions and 77 deletions

View file

@ -0,0 +1,26 @@
// 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 authtypes
// LoginRequest represents the request sent by the client
// https://matrix.org/docs/spec/client_server/r0.3.0.html#post-matrix-client-r0-login
type LoginRequest struct {
Type LoginType `json:"type"`
User string `json:"user"`
Medium string `json:"medium"`
Address string `json:"address"`
Password string `json:"password"`
Token string `json:"token"`
DeviceID string `json:"device_id"`
InitialDisplayName *string `json:"initial_device_display_name"`
}

View file

@ -0,0 +1,26 @@
// 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 authtypes
import (
"github.com/matrix-org/gomatrixserverlib"
)
// LoginResponse represents the response received by the client
// https://matrix.org/docs/spec/client_server/r0.3.0.html#post-matrix-client-r0-login
type LoginResponse struct {
UserID string `json:"user_id"`
AccessToken string `json:"access_token"`
HomeServer gomatrixserverlib.ServerName `json:"home_server"`
DeviceID string `json:"device_id"`
}

View file

@ -9,4 +9,6 @@ const (
LoginTypeSharedSecret = "org.matrix.login.shared_secret" LoginTypeSharedSecret = "org.matrix.login.shared_secret"
LoginTypeRecaptcha = "m.login.recaptcha" LoginTypeRecaptcha = "m.login.recaptcha"
LoginTypeApplicationService = "m.login.application_service" LoginTypeApplicationService = "m.login.application_service"
LoginTypePassword = "m.login.password"
LoginTypeToken = "m.login.token"
) )

View file

@ -19,8 +19,10 @@ import (
"strings" "strings"
"github.com/matrix-org/dendrite/clientapi/auth" "github.com/matrix-org/dendrite/clientapi/auth"
"github.com/matrix-org/dendrite/clientapi/auth/authtypes"
"github.com/matrix-org/dendrite/clientapi/auth/storage/accounts" "github.com/matrix-org/dendrite/clientapi/auth/storage/accounts"
"github.com/matrix-org/dendrite/clientapi/auth/storage/devices" "github.com/matrix-org/dendrite/clientapi/auth/storage/devices"
"github.com/matrix-org/dendrite/clientapi/auth/tokens"
"github.com/matrix-org/dendrite/clientapi/httputil" "github.com/matrix-org/dendrite/clientapi/httputil"
"github.com/matrix-org/dendrite/clientapi/jsonerror" "github.com/matrix-org/dendrite/clientapi/jsonerror"
"github.com/matrix-org/dendrite/common/config" "github.com/matrix-org/dendrite/common/config"
@ -37,42 +39,70 @@ type flow struct {
Stages []string `json:"stages"` Stages []string `json:"stages"`
} }
type passwordRequest struct { func defaultPasswordLogin() loginFlows {
User string `json:"user"`
Password string `json:"password"`
InitialDisplayName *string `json:"initial_device_display_name"`
}
type loginResponse struct {
UserID string `json:"user_id"`
AccessToken string `json:"access_token"`
HomeServer gomatrixserverlib.ServerName `json:"home_server"`
DeviceID string `json:"device_id"`
}
func passwordLogin() loginFlows {
f := loginFlows{} f := loginFlows{}
s := flow{"m.login.password", []string{"m.login.password"}} s := flow{string(authtypes.LoginTypePassword), []string{string(authtypes.LoginTypePassword)}}
f.Flows = append(f.Flows, s) f.Flows = append(f.Flows, s)
return f return f
} }
// GetLocalpartDomainFromUserid extracts localpart & domain of server from userID
// Returns JSON error in case of invalid username.
func GetLocalpartDomainFromUserid(userID string) (
string, gomatrixserverlib.ServerName, *util.JSONResponse) {
localpart, domain, err := gomatrixserverlib.SplitID('@', userID)
if err != nil {
return localpart, domain, &util.JSONResponse{
Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("Invalid username"),
}
}
return localpart, domain, nil
}
// Login implements GET and POST /login // Login implements GET and POST /login
func Login( func Login(
req *http.Request, accountDB *accounts.Database, deviceDB *devices.Database, req *http.Request, accountDB *accounts.Database, deviceDB *devices.Database,
cfg config.Dendrite, cfg config.Dendrite,
) util.JSONResponse { ) util.JSONResponse {
if req.Method == http.MethodGet { // TODO: support other forms of login other than password, depending on config options if req.Method == http.MethodGet {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
JSON: passwordLogin(), JSON: defaultPasswordLogin(),
} }
} else if req.Method == http.MethodPost { } else if req.Method == http.MethodPost {
var r passwordRequest var r authtypes.LoginRequest
resErr := httputil.UnmarshalJSONRequest(req, &r) resErr := httputil.UnmarshalJSONRequest(req, &r)
if resErr != nil { if resErr != nil {
return *resErr return *resErr
} }
util.GetLogger(req.Context()).WithField("user", r.User).Info("Processing login request")
switch r.Type {
case authtypes.LoginTypePassword:
return handlePasswordLogin(r, accountDB, deviceDB, req, cfg)
case authtypes.LoginTypeToken:
return handleTokenLogin(r, deviceDB, req, cfg)
default:
return util.JSONResponse{
Code: http.StatusNotImplemented,
JSON: jsonerror.Unknown("Unknown login type"),
}
}
}
return util.JSONResponse{
Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"),
}
}
func handlePasswordLogin(
r authtypes.LoginRequest, accountDB *accounts.Database, deviceDB *devices.Database,
req *http.Request, cfg config.Dendrite) util.JSONResponse {
if r.User == "" { if r.User == "" {
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusBadRequest, Code: http.StatusBadRequest,
@ -80,19 +110,16 @@ func Login(
} }
} }
util.GetLogger(req.Context()).WithField("user", r.User).Info("Processing login request")
// r.User can either be a user ID or just the localpart... or other things maybe. // r.User can either be a user ID or just the localpart... or other things maybe.
localpart := r.User localpart := r.User
if strings.HasPrefix(r.User, "@") { if strings.HasPrefix(r.User, "@") {
var domain gomatrixserverlib.ServerName var domain gomatrixserverlib.ServerName
var err error var err *util.JSONResponse
localpart, domain, err = gomatrixserverlib.SplitID('@', r.User)
localpart, domain, err = GetLocalpartDomainFromUserid(r.User)
if err != nil { if err != nil {
return util.JSONResponse{ return *err
Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("Invalid username"),
}
} }
if domain != cfg.Matrix.ServerName { if domain != cfg.Matrix.ServerName {
@ -103,7 +130,8 @@ func Login(
} }
} }
acc, err := accountDB.GetAccountByPassword(req.Context(), localpart, r.Password) _, err := accountDB.GetAccountByPassword(req.Context(), localpart, r.Password)
if err != nil { if err != nil {
// Technically we could tell them if the user does not exist by checking if err == sql.ErrNoRows // Technically we could tell them if the user does not exist by checking if err == sql.ErrNoRows
// but that would leak the existence of the user. // but that would leak the existence of the user.
@ -113,14 +141,98 @@ func Login(
} }
} }
token, err := auth.GenerateAccessToken() var token string
token, err = tokens.GenerateLoginToken(tokens.TokenOptions{
ServerMacaroonSecret: []byte(string(cfg.Matrix.PrivateKey)),
ServerName: string(cfg.Matrix.ServerName),
UserID: r.User,
})
if err != nil {
return util.JSONResponse{
Code: http.StatusNotImplemented,
JSON: jsonerror.Unknown("Token generation failed"),
}
}
util.GetLogger(req.Context()).WithField("user", r.User).Info(token)
return completeLogin(r, localpart, deviceDB, req, cfg)
}
func handleTokenLogin(
r authtypes.LoginRequest, deviceDB *devices.Database,
req *http.Request, cfg config.Dendrite) util.JSONResponse {
if r.Token == "" {
return util.JSONResponse{
Code: http.StatusUnauthorized,
JSON: jsonerror.MissingToken("Missing login token"),
}
}
// UserID may be left empty for token based login
userID := r.User
if userID == "" {
var err error
userID, err = tokens.GetUserFromToken(r.Token)
if err != nil {
return util.JSONResponse{
Code: http.StatusUnauthorized,
JSON: jsonerror.UnknownToken(err.Error()),
}
}
}
// r.User can either be a user ID or just the localpart... or other things maybe.
localpart := userID
if strings.HasPrefix(userID, "@") {
var domain gomatrixserverlib.ServerName
var resErr *util.JSONResponse
localpart, domain, resErr = GetLocalpartDomainFromUserid(r.User)
if resErr != nil {
return *resErr
}
if domain != cfg.Matrix.ServerName {
return util.JSONResponse{
Code: http.StatusBadRequest,
JSON: jsonerror.InvalidUsername("User ID not ours"),
}
}
}
tokenOptions := tokens.TokenOptions{
ServerMacaroonSecret: []byte(string(cfg.Matrix.PrivateKey)),
ServerName: string(cfg.Matrix.ServerName),
UserID: userID,
}
resErr := tokens.ValidateToken(tokenOptions, r.Token)
if resErr != nil {
return *resErr
}
return completeLogin(r, localpart, deviceDB, req, cfg)
}
// completeLogin completes the login process after the client request has been
// authenticated by one of the supported methods.
func completeLogin(r authtypes.LoginRequest, localpart string,
deviceDB *devices.Database, req *http.Request, cfg config.Dendrite,
) util.JSONResponse {
accessToken, err := auth.GenerateAccessToken()
if err != nil { if err != nil {
httputil.LogThenError(req, err) httputil.LogThenError(req, err)
} }
// TODO: Use the device ID in the request // TODO: Use the device ID in the request
dev, err := deviceDB.CreateDevice( dev, err := deviceDB.CreateDevice(
req.Context(), acc.Localpart, nil, token, r.InitialDisplayName, req.Context(), localpart, nil, accessToken, r.InitialDisplayName,
) )
if err != nil { if err != nil {
return util.JSONResponse{ return util.JSONResponse{
@ -131,16 +243,11 @@ func Login(
return util.JSONResponse{ return util.JSONResponse{
Code: http.StatusOK, Code: http.StatusOK,
JSON: loginResponse{ JSON: authtypes.LoginResponse{
UserID: dev.UserID, UserID: dev.UserID,
AccessToken: dev.AccessToken, AccessToken: dev.AccessToken,
HomeServer: cfg.Matrix.ServerName, HomeServer: cfg.Matrix.ServerName,
DeviceID: dev.ID, DeviceID: dev.ID,
}, },
} }
}
return util.JSONResponse{
Code: http.StatusMethodNotAllowed,
JSON: jsonerror.NotFound("Bad method"),
}
} }