Skip to content

Commit f9d1aaf

Browse files
Implement authentication methods and update middleware function
1 parent 8acb100 commit f9d1aaf

File tree

2 files changed

+53
-3
lines changed

2 files changed

+53
-3
lines changed

src/middleware.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
import { NextResponse } from "next/server";
2-
import type { NextRequest } from "next/server";
2+
// import type { NextRequest } from "next/server";
33
import getOrCreateDB from "./models/server/dbSetup";
44
import getOrCreateStorage from "./models/server/storageSetup";
55

66
//as this is my middleware this function can everywhere we want
7-
export async function middleware(request: NextRequest){
7+
export async function middleware(){
88

99
await Promise.all([
1010
getOrCreateDB(),

src/store/Auth.ts

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,58 @@ export const useAuthStore = create<AuthStore>()(
4242
set({hydrated: true})
4343
},
4444

45-
45+
async verifySession() {
46+
try {
47+
const session = await account.getSession("current");
48+
set({session});
49+
} catch (error) {
50+
console.log("Error verifying session", error);
51+
}
52+
},
53+
54+
async login(email, password) {
55+
try {
56+
const session = await account.createEmailPasswordSession(email, password);
57+
const [user, {jwt}] = await Promise.all([
58+
account.get<UserPrefs>(),
59+
account.createJWT()
60+
])
61+
if(!user.prefs?.reputation) await account.updatePrefs<UserPrefs>({reputation: 0});
62+
set({session, user, jwt});
63+
return {success: true, };
64+
} catch (error) {
65+
console.log("Error logging in", error);
66+
return {
67+
success: false,
68+
error: error instanceof AppwriteException ? error : null
69+
};
70+
}
71+
},
72+
73+
async createAccount(name:string, email:string, password:string) {
74+
try {
75+
await account.create(ID.unique() ,name, email, password);
76+
return {success: true};
77+
} catch (error) {
78+
console.log("Error creating account", error);
79+
return {
80+
success: false,
81+
error: error instanceof AppwriteException ? error : null
82+
};
83+
}
84+
},
85+
86+
async logout() {
87+
try {
88+
await account.deleteSessions();
89+
set({session: null, jwt:null, user: null});
90+
} catch (error) {
91+
console.log("Error logout", error);
92+
}
93+
},
4694
})),
95+
96+
//for immer to work we need to use the immer middleware
4797
{
4898
name: "auth",
4999
onRehydrateStorage(){

0 commit comments

Comments
 (0)