Skip to content

Commit

Permalink
add: login
Browse files Browse the repository at this point in the history
  • Loading branch information
zrll12 committed Nov 11, 2023
1 parent 088a3f2 commit ab7bcc4
Show file tree
Hide file tree
Showing 10 changed files with 127 additions and 82 deletions.
10 changes: 5 additions & 5 deletions app/authenticate/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ import {Button} from "@nextui-org/button";
import React, {ReactNode, useState} from "react";
import {Input} from "@nextui-org/input";
import {Checkbox} from "@nextui-org/checkbox";
import {User} from "@/interface/api";
import {Message} from "@/components/message";
import {useRouter} from "next/navigation";
import {UserModel} from "@/interface/model/user";
import {SetLoggedInState} from "@/interface/hooks";
import {UserAPI} from "@/interface/user";

type colors = "default" | "primary" | "secondary" | "success" | "warning" | "danger" | undefined;

Expand All @@ -30,7 +30,7 @@ export default function Page() {

let router = useRouter();

User.loginSession().then(([state, user]) => {
UserAPI.loginSession().then(([state, user]) => {
if (state) {
router.push("/dashboard");
let userModel: UserModel = JSON.parse(user);
Expand Down Expand Up @@ -128,7 +128,7 @@ export default function Page() {
}
setLoading(true);
setButtonDisable(true);
User.checkEmail(email).then(r => {
UserAPI.checkEmail(email).then(r => {
setState(r ? "login" : "register")
setButtonDisable(false);
setLoading(false);
Expand All @@ -143,7 +143,7 @@ export default function Page() {
if (password != confirmPassword) {
Message.error("密码输入不一致")
}
User.creatUser(email, password, username, code).then(r => {
UserAPI.creatUser(email, password, username, code).then(r => {
let [status, message] = r;
if (status) {
Message.success("注册成功,请登录");
Expand All @@ -161,7 +161,7 @@ export default function Page() {
setLoading(true);
setButtonDisable(true);

User.login(email, password).then((r) => {
UserAPI.login(email, password).then((r) => {
let [state, text] = r;

if (state) {
Expand Down
5 changes: 4 additions & 1 deletion app/dashboard/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {useRouter} from "next/navigation";
import {Chip} from "@nextui-org/chip";
import {FiChevronsUp, FiUploadCloud} from "react-icons/fi";
import Picture from "@/components/picture";
import {PictureAPI} from "@/interface/pictureAPI";

export default function Page() {
let used = 1050;
Expand Down Expand Up @@ -45,8 +46,10 @@ export default function Page() {
<span>上传文件</span>
</a>
} onChange={(e) => {
let file = e.target.files;
let files = e.target.files!;
console.log(e.target.files);
let file = files[0];
PictureAPI.uploadFile(file).then(() => {});
}}></Uploader>

<Button className="bg-gradient-to-tr from-pink-500 to-yellow-500 text-white" onClick={() => {
Expand Down
5 changes: 3 additions & 2 deletions app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {Button} from "@nextui-org/button";
import {HiOutlineNewspaper} from "react-icons/hi";
import {FaLocationArrow} from "react-icons/fa6";
import {BsLightbulb} from "react-icons/bs";
import {IsLoggedIn} from "@/interface/hooks";

export default function Home() {
return (
Expand All @@ -29,7 +30,7 @@ export default function Home() {
<div className="flex gap-3">
<Link
as={NextLink}
href={"/pricing"}
href={IsLoggedIn ? "/pricing" : "/dashboard"}
className={buttonStyles({color: "primary", variant: "shadow"})}
>
<FaLocationArrow size={20}/>
Expand Down Expand Up @@ -118,7 +119,7 @@ export default function Home() {
<CardFooter
className="absolute bg-black/40 bottom-0 z-10 border-t-1 border-default-600 dark:border-default-100">
<div className="flex flex-grow gap-2 items-center">
<BsLightbulb />
<BsLightbulb color="white"/>
<div className="flex flex-col">
<p className="text-tiny text-white/60">有疑问,还是好点子?</p>
<p className="text-tiny text-white/60">快来和我们分享一下吧!</p>
Expand Down
8 changes: 6 additions & 2 deletions app/pricing/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@

import {title} from "@/components/primitives";
import {Price} from "@/components/price";
import {priceFree, priceStarted, priceAdvanced, priceProfessional} from "@/config/prices";
import {priceAdvanced, priceFree, priceProfessional, priceStarted} from "@/config/prices";
import {Tab, Tabs} from "@nextui-org/react";
import {PiFireDuotone} from "react-icons/pi";

export default function PricingPage() {
return (
Expand All @@ -18,7 +19,10 @@ export default function PricingPage() {
<Tab key="started" title="入门">
<Price price={priceStarted}/>
</Tab>
<Tab key="advanced" title="进阶">
<Tab key="advanced" title={<div className="flex space-x-0.5 items-center">
<span>进阶</span>
<PiFireDuotone style={{color: "red"}} size={17}/>
</div>}>
<Price price={priceAdvanced}/>
</Tab>
<Tab key="professional" title="专业">
Expand Down
2 changes: 1 addition & 1 deletion components/navbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ import {Message} from "@/components/message";
export const Navbar = () => {
let router = useRouter();
let [loggedIn, setLoggedIn] = useState(cookie.load("token") != undefined);

UpdateSetLoggedInHook(setLoggedIn);

return (
<NextUINavbar maxWidth="xl" position="sticky">
<NavbarContent className="basis-1/5 sm:basis-full" justify="start">
Expand Down
1 change: 1 addition & 0 deletions components/picture.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export default function Picture(props: PictureProps) {
isFooterBlurred
radius="lg"
className="border-none items-center"
isPressable
>
<Image
alt="Woman listing to music"
Expand Down
70 changes: 0 additions & 70 deletions interface/api.ts
Original file line number Diff line number Diff line change
@@ -1,73 +1,3 @@
import cookie from "react-cookies";

export const SERVER_URL = "http://127.0.0.1:8102";

export class User {
static async checkEmail(email: string): Promise<boolean> {
//request
var requestOptions: RequestInit = {
method: 'GET',
redirect: 'follow'
};

let response = await fetch(SERVER_URL + "/user/email/" + email, requestOptions);

return await response.text() == "exists";
}

static async creatUser(email: string, password: string, username: string, code: string): Promise<[boolean, string]> {

let formData = new FormData();
formData.append("email", email);
formData.append("password", password);
formData.append("username", username);
formData.append("code", code);

let requestOptions: RequestInit = {
method: 'POST',
body: formData,
redirect: 'follow'
};

let response = await fetch(SERVER_URL + "/user", requestOptions);
let text = await response.text();

return [response.ok, text];
}

static async login(username: String, password: String): Promise<[boolean, string]> {
let requestOptions: RequestInit = {
method: 'GET',
redirect: 'follow'
};

let response = await fetch(SERVER_URL + "/user?username=" + username + "&password=" + password, requestOptions);

if (response.ok) {
cookie.save("token", response.headers.get("token")!, {});
}

return [response.ok, await response.text()]
}

static async loginSession(): Promise<[boolean, string]> {
if (cookie.load("token") == null) {
return [false, ""];
}


let headers = new Headers();
headers.append("token", cookie.load("token"));

let requestOptions: RequestInit = {
method: 'GET',
redirect: 'follow',
headers: headers
};

let response = await fetch(SERVER_URL + "/user", requestOptions);
cookie.save("token", response.headers.get("token")!, {});

return [response.ok, await response.text()];
}
}
8 changes: 7 additions & 1 deletion interface/hooks.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import cookie from "react-cookies";

export var SetLoggedInState: any = null;
export var IsLoggedIn: boolean = !cookie.load("token") == undefined;

export function UpdateSetLoggedInHook(hook: any) {
SetLoggedInState = hook;
SetLoggedInState = (loggedIn: boolean) => {
hook(loggedIn);
IsLoggedIn = loggedIn;
};
}
28 changes: 28 additions & 0 deletions interface/pictureAPI.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import {SERVER_URL} from "@/interface/api";
import {base} from "next/dist/build/webpack/config/blocks/base";

export class PictureAPI {
static async uploadFile(file: File) {
let formData = new FormData();
formData.append("file", file);

let requestOptions: RequestInit = {
method: 'POST',
body: formData,
redirect: 'follow'
};

fetch(SERVER_URL + "/picture?name=" + file.name, requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
}
}
async function getBase64(file: File): Promise<string> {
return new Promise((resolve, reject) => {
let reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result as string);
reader.onerror = (error) => reject(error);
})
}
72 changes: 72 additions & 0 deletions interface/user.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import cookie from "react-cookies";
import {SERVER_URL} from "@/interface/api";

export class UserAPI {
static async checkEmail(email: string): Promise<boolean> {
//request
var requestOptions: RequestInit = {
method: 'GET',
redirect: 'follow'
};

let response = await fetch(SERVER_URL + "/user/email/" + email, requestOptions);

return await response.text() == "exists";
}

static async creatUser(email: string, password: string, username: string, code: string): Promise<[boolean, string]> {

let formData = new FormData();
formData.append("email", email);
formData.append("password", password);
formData.append("username", username);
formData.append("code", code);

let requestOptions: RequestInit = {
method: 'POST',
body: formData,
redirect: 'follow'
};

let response = await fetch(SERVER_URL + "/user", requestOptions);
let text = await response.text();

return [response.ok, text];
}

static async login(username: String, password: String): Promise<[boolean, string]> {
let requestOptions: RequestInit = {
method: 'GET',
redirect: 'follow'
};

let response = await fetch(SERVER_URL + "/user?email=" + username + "&password=" + password, requestOptions);

if (response.ok) {
cookie.save("token", response.headers.get("token")!, {});
}

return [response.ok, await response.text()]
}

static async loginSession(): Promise<[boolean, string]> {
if (cookie.load("token") == null) {
return [false, ""];
}


let headers = new Headers();
headers.append("token", cookie.load("token"));

let requestOptions: RequestInit = {
method: 'GET',
redirect: 'follow',
headers: headers
};

let response = await fetch(SERVER_URL + "/user", requestOptions);
cookie.save("token", response.headers.get("token")!, {});

return [response.ok, await response.text()];
}
}

0 comments on commit ab7bcc4

Please sign in to comment.