2019-02-02 16:18:25 +08:00
|
|
|
// Copyright 2018 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
2018-08-24 18:23:26 +08:00
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2018-08-24 18:23:26 +08:00
|
|
|
|
|
|
|
package ghttp
|
|
|
|
|
|
|
|
import (
|
2019-06-19 09:06:52 +08:00
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"strings"
|
2019-07-02 16:56:10 +08:00
|
|
|
|
2019-07-29 21:01:19 +08:00
|
|
|
"github.com/gogf/gf/encoding/gbase64"
|
2018-08-24 18:23:26 +08:00
|
|
|
)
|
|
|
|
|
2020-02-11 10:00:10 +08:00
|
|
|
// BasicAuth enables the http basic authentication feature with given passport and password
|
|
|
|
// and asks client for authentication. It returns true if authentication success, else returns
|
|
|
|
// false if failure.
|
2019-06-19 09:06:52 +08:00
|
|
|
func (r *Request) BasicAuth(user, pass string, tips ...string) bool {
|
|
|
|
auth := r.Header.Get("Authorization")
|
|
|
|
if auth == "" {
|
|
|
|
r.setBasicAuth(tips...)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
authArray := strings.SplitN(auth, " ", 2)
|
|
|
|
if len(authArray) != 2 {
|
|
|
|
r.Response.WriteStatus(http.StatusForbidden)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
switch authArray[0] {
|
|
|
|
case "Basic":
|
2019-07-02 16:56:10 +08:00
|
|
|
authBytes, err := gbase64.DecodeString(authArray[1])
|
2019-06-19 09:06:52 +08:00
|
|
|
if err != nil {
|
|
|
|
r.Response.WriteStatus(http.StatusForbidden, err.Error())
|
|
|
|
return false
|
|
|
|
}
|
2019-07-02 16:56:10 +08:00
|
|
|
authArray := strings.SplitN(string(authBytes), ":", 2)
|
2019-06-19 09:06:52 +08:00
|
|
|
if len(authArray) != 2 {
|
|
|
|
r.Response.WriteStatus(http.StatusForbidden)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
if authArray[0] != user || authArray[1] != pass {
|
|
|
|
r.setBasicAuth(tips...)
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
2018-08-24 18:23:26 +08:00
|
|
|
|
2019-06-19 09:06:52 +08:00
|
|
|
default:
|
|
|
|
r.Response.WriteStatus(http.StatusForbidden)
|
|
|
|
return false
|
|
|
|
}
|
2020-04-06 22:31:45 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
// setBasicAuth sets the http basic authentication tips.
|
|
|
|
func (r *Request) setBasicAuth(tips ...string) {
|
|
|
|
realm := ""
|
|
|
|
if len(tips) > 0 && tips[0] != "" {
|
|
|
|
realm = tips[0]
|
|
|
|
} else {
|
|
|
|
realm = "Need Login"
|
|
|
|
}
|
|
|
|
r.Response.Header().Set("WWW-Authenticate", fmt.Sprintf(`Basic realm="%s"`, realm))
|
|
|
|
r.Response.WriteHeader(http.StatusUnauthorized)
|
2018-08-24 18:23:26 +08:00
|
|
|
}
|