feat: turing test before send code

Signed-off-by: Kininaru <shiftregister233@outlook.com>

i18n

i18n

Signed-off-by: Kininaru <shiftregister233@outlook.com>
This commit is contained in:
Kininaru
2021-05-22 20:57:55 +08:00
parent 665e77b797
commit f39378562f
12 changed files with 217 additions and 91 deletions

View File

@ -87,6 +87,7 @@ p, *, *, POST, /api/upload-avatar, *, *
p, *, *, POST, /api/unlink, *, * p, *, *, POST, /api/unlink, *, *
p, *, *, POST, /api/set-password, *, * p, *, *, POST, /api/set-password, *, *
p, *, *, POST, /api/send-verification-code, *, * p, *, *, POST, /api/send-verification-code, *, *
p, *, *, GET, /api/get-human-check, *, *
` `
sa := stringadapter.NewAdapter(ruleText) sa := stringadapter.NewAdapter(ruleText)

View File

@ -59,6 +59,14 @@ type Response struct {
Data2 interface{} `json:"data2"` Data2 interface{} `json:"data2"`
} }
type HumanCheck struct {
Type string `json:"type"`
AppKey string `json:"appKey"`
Scene string `json:"scene"`
CaptchaId string `json:"captchaId"`
CaptchaImage interface{} `json:"captchaImage"`
}
// @Title Signup // @Title Signup
// @Description sign up a new user // @Description sign up a new user
// @Param username formData string true "The username to sign up" // @Param username formData string true "The username to sign up"
@ -216,3 +224,17 @@ func (c *ApiController) UploadAvatar() {
c.Data["json"] = resp c.Data["json"] = resp
c.ServeJSON() c.ServeJSON()
} }
func (c *ApiController) GetHumanCheck() {
c.Data["json"] = HumanCheck{Type: "none"}
provider := object.GetDefaultHumanCheckProvider()
if provider == nil {
id, img := object.GetCaptcha()
c.Data["json"] = HumanCheck{Type: "captcha", CaptchaId: id, CaptchaImage: img}
c.ServeJSON()
return
}
c.ServeJSON()
}

View File

@ -26,14 +26,28 @@ func (c *ApiController) SendVerificationCode() {
destType := c.Ctx.Request.Form.Get("type") destType := c.Ctx.Request.Form.Get("type")
dest := c.Ctx.Request.Form.Get("dest") dest := c.Ctx.Request.Form.Get("dest")
orgId := c.Ctx.Request.Form.Get("organizationId") orgId := c.Ctx.Request.Form.Get("organizationId")
checkType := c.Ctx.Request.Form.Get("checkType")
checkId := c.Ctx.Request.Form.Get("checkId")
checkKey := c.Ctx.Request.Form.Get("checkKey")
remoteAddr := c.Ctx.Request.RemoteAddr remoteAddr := c.Ctx.Request.RemoteAddr
remoteAddr = remoteAddr[:strings.LastIndex(remoteAddr, ":")] remoteAddr = remoteAddr[:strings.LastIndex(remoteAddr, ":")]
if len(destType) == 0 || len(dest) == 0 || len(orgId) == 0 || strings.Index(orgId, "/") < 0 { if len(destType) == 0 || len(dest) == 0 || len(orgId) == 0 || strings.Index(orgId, "/") < 0 || len(checkType) == 0 || len(checkId) == 0 || len(checkKey) == 0 {
c.ResponseError("Missing parameter.") c.ResponseError("Missing parameter.")
return return
} }
isHuman := false
provider := object.GetDefaultHumanCheckProvider()
if provider == nil {
isHuman = object.VerifyCaptcha(checkId, checkKey)
}
if !isHuman {
c.ResponseError("Turing test failed.")
return
}
msg := "Invalid dest type." msg := "Invalid dest type."
switch destType { switch destType {
case "email": case "email":

View File

@ -96,6 +96,20 @@ func getDefaultPhoneProvider() *Provider {
return &provider return &provider
} }
func GetDefaultHumanCheckProvider() *Provider {
provider := Provider{Owner: "admin", Category: "HumanCheck"}
existed, err := adapter.Engine.Get(&provider)
if err != nil {
panic(err)
}
if !existed {
return nil
}
return &provider
}
func UpdateProvider(id string, provider *Provider) bool { func UpdateProvider(id string, provider *Provider) bool {
owner, name := util.GetOwnerAndNameFromId(id) owner, name := util.GetOwnerAndNameFromId(id)
if getProvider(owner, name) == nil { if getProvider(owner, name) == nil {

View File

@ -62,6 +62,7 @@ func initAPI() {
beego.Router("/api/set-password", &controllers.ApiController{}, "POST:SetPassword") beego.Router("/api/set-password", &controllers.ApiController{}, "POST:SetPassword")
beego.Router("/api/send-verification-code", &controllers.ApiController{}, "POST:SendVerificationCode") beego.Router("/api/send-verification-code", &controllers.ApiController{}, "POST:SendVerificationCode")
beego.Router("/api/reset-email-or-phone", &controllers.ApiController{}, "POST:ResetEmailOrPhone") beego.Router("/api/reset-email-or-phone", &controllers.ApiController{}, "POST:ResetEmailOrPhone")
beego.Router("/api/get-human-check", &controllers.ApiController{}, "GET:GetHumanCheck")
beego.Router("/api/get-providers", &controllers.ApiController{}, "GET:GetProviders") beego.Router("/api/get-providers", &controllers.ApiController{}, "GET:GetProviders")
beego.Router("/api/get-provider", &controllers.ApiController{}, "GET:GetProvider") beego.Router("/api/get-provider", &controllers.ApiController{}, "GET:GetProvider")

View File

@ -17,7 +17,7 @@ import i18next from "i18next";
import React from "react"; import React from "react";
import * as Setting from "./Setting" import * as Setting from "./Setting"
import * as UserBackend from "./backend/UserBackend" import * as UserBackend from "./backend/UserBackend"
import {CountDownInput} from "./reusable/CountDownInput"; import {CountDownInput} from "./component/CountDownInput";
export const ResetModal = (props) => { export const ResetModal = (props) => {
const [visible, setVisible] = React.useState(false); const [visible, setVisible] = React.useState(false);
@ -55,21 +55,6 @@ export const ResetModal = (props) => {
}) })
} }
const sendCode = () => {
if (dest === "") {
Setting.showMessage("error", i18next.t("user:Empty " + destType));
return;
}
let orgId = org.owner + "/" + org.name;
UserBackend.sendCode(dest, destType, orgId).then(res => {
if (res.status === "ok") {
Setting.showMessage("success", i18next.t("user:Code Sent"));
} else {
Setting.showMessage("error", i18next.t("user:" + res.msg));
}
})
}
let placeHolder = ""; let placeHolder = "";
if (destType === "email") placeHolder = i18next.t("user:Input your email"); if (destType === "email") placeHolder = i18next.t("user:Input your email");
else if (destType === "phone") placeHolder = i18next.t("user:Input your phone number"); else if (destType === "phone") placeHolder = i18next.t("user:Input your phone number");
@ -103,7 +88,8 @@ export const ResetModal = (props) => {
textBefore={i18next.t("user:Code You Received")} textBefore={i18next.t("user:Code You Received")}
placeHolder={i18next.t("user:Enter your code")} placeHolder={i18next.t("user:Enter your code")}
onChange={setCode} onChange={setCode}
onButtonClick={sendCode} onButtonClick={UserBackend.sendCode}
onButtonClickArgs={[dest, destType, org?.owner + "/" + org?.name]}
coolDownTime={coolDownTime} coolDownTime={coolDownTime}
/> />
</Row> </Row>

View File

@ -22,7 +22,7 @@ import * as Util from "./Util";
import {authConfig} from "./Auth"; import {authConfig} from "./Auth";
import * as ApplicationBackend from "../backend/ApplicationBackend"; import * as ApplicationBackend from "../backend/ApplicationBackend";
import * as UserBackend from "../backend/UserBackend"; import * as UserBackend from "../backend/UserBackend";
import {CountDownInput} from "../reusable/CountDownInput"; import {CountDownInput} from "../component/CountDownInput";
const formItemLayout = { const formItemLayout = {
labelCol: { labelCol: {
@ -117,22 +117,6 @@ class SignupPage extends React.Component {
this.form.current.scrollToField(errorFields[0].name); this.form.current.scrollToField(errorFields[0].name);
} }
sendCode(type) {
let dest, orgId;
if (type === "email") {
dest = this.state.email;
} else if (type === "phone") {
dest = this.state.phone;
} else return;
orgId = this.state.application?.organizationObj.owner + "/" + this.state.application?.organizationObj.name
UserBackend.sendCode(dest, type, orgId).then(res => {
if (res.status === "ok") Setting.showMessage("success", i18next.t("signup:code sent"));
else Setting.showMessage("error", i18next.t("signup:" + res.msg));
})
}
renderForm(application) { renderForm(application) {
if (!application.enableSignUp) { if (!application.enableSignUp) {
return ( return (
@ -255,7 +239,8 @@ class SignupPage extends React.Component {
> >
<CountDownInput <CountDownInput
defaultButtonText={i18next.t("signup:send code")} defaultButtonText={i18next.t("signup:send code")}
onButtonClick={() => this.sendCode("email")} onButtonClick={UserBackend.sendCode}
onButtonClickArgs={[this.state.email, "email", this.state.application?.organizationObj.owner + "/" + this.state.application?.organizationObj.name]}
coolDownTime={60} coolDownTime={60}
/> />
</Form.Item> </Form.Item>
@ -325,7 +310,8 @@ class SignupPage extends React.Component {
> >
<CountDownInput <CountDownInput
defaultButtonText={i18next.t("signup:send code")} defaultButtonText={i18next.t("signup:send code")}
onButtonClick={() => this.sendCode("phone")} onButtonClick={UserBackend.sendCode}
onButtonClickArgs={[this.state.phone, "phone", this.state.application?.organizationObj.owner + "/" + this.state.application?.organizationObj.name]}
coolDownTime={60} coolDownTime={60}
/> />
</Form.Item> </Form.Item>

View File

@ -14,6 +14,7 @@
import * as Setting from "../Setting"; import * as Setting from "../Setting";
import * as AuthBackend from "../auth/AuthBackend"; import * as AuthBackend from "../auth/AuthBackend";
import i18next from "i18next";
export function getGlobalUsers() { export function getGlobalUsers() {
return fetch(`${Setting.ServerUrl}/api/get-global-users`, { return fetch(`${Setting.ServerUrl}/api/get-global-users`, {
@ -93,8 +94,11 @@ export function setPassword(userOwner, userName, oldPassword, newPassword) {
}).then(res => res.json()); }).then(res => res.json());
} }
export function sendCode(dest, type, orgId) { export function sendCode(checkType, checkId, checkKey, dest, type, orgId) {
let formData = new FormData(); let formData = new FormData();
formData.append("checkType", checkType);
formData.append("checkId", checkId);
formData.append("checkKey", checkKey);
formData.append("dest", dest); formData.append("dest", dest);
formData.append("type", type); formData.append("type", type);
formData.append("organizationId", orgId); formData.append("organizationId", orgId);
@ -102,7 +106,15 @@ export function sendCode(dest, type, orgId) {
method: "POST", method: "POST",
credentials: "include", credentials: "include",
body: formData body: formData
}).then(res => res.json()); }).then(res => res.json()).then(res => {
if (res.status === "ok") {
Setting.showMessage("success", i18next.t("user:Code Sent"));
return true;
} else {
Setting.showMessage("error", i18next.t("user:" + res.msg));
return false;
}
});
} }
export function resetEmailOrPhone(dest, type, code) { export function resetEmailOrPhone(dest, type, code) {
@ -116,3 +128,9 @@ export function resetEmailOrPhone(dest, type, code) {
body: formData body: formData
}).then(res => res.json()); }).then(res => res.json());
} }
export function getHumanCheck() {
return fetch(`${Setting.ServerUrl}/api/get-human-check`, {
method: "GET"
}).then(res => res.json());
}

View File

@ -0,0 +1,126 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import {Col, Input, Modal, Row} from "antd";
import React from "react";
import * as Setting from "../Setting";
import i18next from "i18next";
import * as UserBackend from "../backend/UserBackend";
export const CountDownInput = (props) => {
const {defaultButtonText, textBefore, placeHolder, onChange, coolDownTime, onButtonClick, onButtonClickArgs} = props;
const [buttonText, setButtonText] = React.useState(defaultButtonText);
const [visible, setVisible] = React.useState(false);
const [key, setKey] = React.useState("");
const [captchaImg, setCaptchaImg] = React.useState("");
const [checkType, setCheckType] = React.useState("");
const [coolDown, setCoolDown] = React.useState(false);
const [checkId, setCheckId] = React.useState("");
const countDown = (leftTime) => {
if (leftTime === 0) {
setCoolDown(false);
setButtonText(defaultButtonText);
return;
}
setButtonText(`${leftTime} s`);
setTimeout(() => countDown(leftTime - 1), 1000);
}
const clickButton = () => {
if (coolDown) {
Setting.showMessage("error", i18next.t("general:Cooling down"));
return;
}
loadHumanCheck();
}
const handleOk = () => {
setVisible(false);
onButtonClick(checkType, checkId, key, ...onButtonClickArgs).then(res => {
if (res) {
setCoolDown(true);
countDown(coolDownTime);
}
})
}
const handleCancel = () => {
setVisible(false);
}
const loadHumanCheck = () => {
UserBackend.getHumanCheck().then(res => {
if (res.type === "none") {
onButtonClick("none", "", "", ...onButtonClickArgs);
} else if (res.type === "captcha") {
setCheckId(res.captchaId);
setCaptchaImg(res.captchaImage);
setCheckType("captcha");
setVisible(true);
} else {
Setting.showMessage("error", i18next.t("signup:Unknown Check Type"));
}
})
}
const renderCaptcha = () => {
return (
<Col>
<Row
style={{
backgroundImage: `url('data:image/png;base64,${captchaImg}')`,
backgroundRepeat: "no-repeat",
height: "80px",
width: "200px",
borderRadius: "3px",
border: "1px solid #ccc",
marginBottom: 10
}}
/>
<Row>
<Input placeholder={i18next.t("general:Enter the code")} onChange={e => setKey(e.target.value)} />
</Row>
</Col>
)
}
const renderCheck = () => {
if (checkType === "captcha") return renderCaptcha();
return null;
}
return (
<Input
addonBefore={textBefore}
placeholder={placeHolder}
onChange={e => onChange(e.target.value)}
addonAfter={
<div>
<button
onClick={clickButton}
style={{backgroundColor: "#fafafa", border: "none"}}>
{buttonText}
</button>
<Modal
visible={visible}
onCancel={handleCancel}
onOk={handleOk}
>
{renderCheck()}
</Modal>
</div>
}/>
);
}

View File

@ -30,7 +30,8 @@
"OAuth providers": "OAuth providers", "OAuth providers": "OAuth providers",
"Applications that requires authentication": "Applications that requires authentication", "Applications that requires authentication": "Applications that requires authentication",
"Swagger": "Swagger", "Swagger": "Swagger",
"Phone Prefix": "Phone Prefix" "Phone Prefix": "Phone Prefix",
"Enter the code": "Enter the code"
}, },
"signup": "signup":
{ {
@ -156,7 +157,9 @@
"You should verify your code in 5 min!": "You should verify your code in 5 min!", "You should verify your code in 5 min!": "You should verify your code in 5 min!",
"Wrong code!": "Wrong code!", "Wrong code!": "Wrong code!",
"Invalid phone number": "Invalid phone number", "Invalid phone number": "Invalid phone number",
"Invalid Email address": "Invalid Email address" "Invalid Email address": "Invalid Email address",
"Turing test failed.": "Turing test failed.",
"Missing parameter.": "Missing parameter. Please check your form!"
}, },
"application": "application":
{ {

View File

@ -30,7 +30,8 @@
"OAuth providers": "OAuth提供方", "OAuth providers": "OAuth提供方",
"Applications that requires authentication": "需要鉴权的应用", "Applications that requires authentication": "需要鉴权的应用",
"Swagger": "API总览", "Swagger": "API总览",
"Phone Prefix": "手机号前缀" "Phone Prefix": "手机号前缀",
"Enter the code": "输入验证码"
}, },
"signup": "signup":
{ {
@ -156,7 +157,9 @@
"You should verify your code in 5 min!": "验证码已超时。你应该在 5 分钟内完成验证。", "You should verify your code in 5 min!": "验证码已超时。你应该在 5 分钟内完成验证。",
"Wrong code!": "验证码错误!", "Wrong code!": "验证码错误!",
"Invalid phone number": "手机号格式错误", "Invalid phone number": "手机号格式错误",
"Invalid Email address": "邮箱格式错误" "Invalid Email address": "邮箱格式错误",
"Turing test failed.": "图灵验证失败,无法确认你是人类!",
"Missing parameter.": "缺少参数!请确认所有信息都已填写!"
}, },
"application": "application":
{ {

View File

@ -1,48 +0,0 @@
// Copyright 2021 The casbin Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import { Input } from "antd";
import React from "react";
import * as Setting from "../Setting";
import i18next from "i18next";
export const CountDownInput = (props) => {
const {defaultButtonText, textBefore, placeHolder, onChange, onButtonClick, coolDownTime} = props;
const [buttonText, setButtonText] = React.useState(defaultButtonText);
let coolDown = false;
const countDown = (leftTime) => {
if (leftTime === 0) {
coolDown = false;
setButtonText(defaultButtonText);
return;
}
setButtonText(`${leftTime} s`);
setTimeout(() => countDown(leftTime - 1), 1000);
}
const clickButton = () => {
if (coolDown) {
Setting.showMessage("error", i18next.t("general:Cooling down"));
return;
}
onButtonClick();
coolDown = true;
countDown(coolDownTime);
}
return (
<Input addonBefore={textBefore} placeholder={placeHolder} onChange={e => onChange(e.target.value)} addonAfter={<button onClick={clickButton} style={{backgroundColor: "#fafafa", border: "none"}}>{buttonText}</button>}/>
);
}