feat(auth.service): add service and action for update email
This commit is contained in:
parent
8c0956aa56
commit
955b4ccc18
2 changed files with 70 additions and 0 deletions
31
src/app/actions/settings/change-username.ts
Normal file
31
src/app/actions/settings/change-username.ts
Normal file
|
@ -0,0 +1,31 @@
|
|||
'use server';
|
||||
|
||||
import { z } from 'zod';
|
||||
import { action } from '@/lib/safe-action';
|
||||
import { getUserFromCookie } from '@/server/common/session.helpers';
|
||||
import { AuthServiceClass } from '@/server/services/auth/auth.service';
|
||||
import { db } from '@/server/db';
|
||||
import { handleActionError } from '../utils/handle-action-error';
|
||||
|
||||
const input = z.object({ newUsername: z.string().email(), password: z.string() });
|
||||
|
||||
/**
|
||||
* Given the current password and a new username, change the username of the current user.
|
||||
*/
|
||||
export const changeUsernameAction = action(input, async ({ newUsername, password }) => {
|
||||
try {
|
||||
const user = await getUserFromCookie();
|
||||
|
||||
if (!user) {
|
||||
throw new Error('User not found');
|
||||
}
|
||||
|
||||
const authService = new AuthServiceClass(db);
|
||||
|
||||
await authService.changeUsername({ userId: user.id, newUsername, password });
|
||||
|
||||
return { success: true };
|
||||
} catch (e) {
|
||||
return handleActionError(e);
|
||||
}
|
||||
});
|
|
@ -382,6 +382,45 @@ export class AuthServiceClass {
|
|||
return true;
|
||||
};
|
||||
|
||||
public changeUsername = async (params: { newUsername: string; password: string; userId: number }) => {
|
||||
if (getConfig().demoMode) {
|
||||
throw new TranslatedError('server-messages.errors.not-allowed-in-demo');
|
||||
}
|
||||
|
||||
const { newUsername, password, userId } = params;
|
||||
|
||||
const user = await this.queries.getUserById(userId);
|
||||
|
||||
if (!user) {
|
||||
throw new TranslatedError('server-messages.errors.user-not-found');
|
||||
}
|
||||
|
||||
const valid = await argon2.verify(user.password, password);
|
||||
|
||||
if (!valid) {
|
||||
throw new TranslatedError('server-messages.errors.invalid-password');
|
||||
}
|
||||
|
||||
const email = newUsername.trim().toLowerCase();
|
||||
|
||||
if (!validator.isEmail(email)) {
|
||||
throw new TranslatedError('server-messages.errors.invalid-username');
|
||||
}
|
||||
|
||||
const existingUser = await this.queries.getUserByUsername(email);
|
||||
|
||||
if (existingUser) {
|
||||
throw new TranslatedError('server-messages.errors.user-already-exists');
|
||||
}
|
||||
|
||||
await this.queries.updateUser(user.id, { username: email });
|
||||
const cache = new TipiCache('changeUsername');
|
||||
await this.destroyAllSessionsByUserId(user.id, cache);
|
||||
await cache.close();
|
||||
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* Given a userId and a locale, change the user's locale
|
||||
*
|
||||
|
|
Loading…
Reference in a new issue