Skip to content

Commit

Permalink
Finalize
Browse files Browse the repository at this point in the history
  • Loading branch information
InfiniteStash committed Nov 14, 2024
1 parent 681d77e commit 77a9cdb
Show file tree
Hide file tree
Showing 12 changed files with 116 additions and 89 deletions.
1 change: 0 additions & 1 deletion frontend/src/graphql/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ export type Scalars = {

export type ActivateNewUserInput = {
activation_key: Scalars["ID"];
email: Scalars["String"];
name: Scalars["String"];
password: Scalars["String"];
};
Expand Down
4 changes: 1 addition & 3 deletions frontend/src/pages/activateUser/ActivateUser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,7 @@ import { ROUTE_HOME, ROUTE_LOGIN } from "src/constants/route";
import Title from "src/components/title";

const schema = yup.object({
name: yup
.string()
.required("Username is required"),
name: yup.string().required("Username is required"),
activationKey: yup.string().required("Activation Key is required"),
password: yup.string().required("Password is required"),
});
Expand Down
4 changes: 3 additions & 1 deletion frontend/src/pages/resetPassword/ResetPassword.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,9 @@ const ResetPassword: FC = () => {
placeholder="New Password"
{...register("newPassword")}
/>
<div className="invalid-feedback">{errors?.newPassword?.message}</div>
<div className="invalid-feedback">
{errors?.newPassword?.message}
</div>
</Form.Group>
<Form.Group controlId="confirmNewPassword" className="mb-3">
<Form.Control
Expand Down
11 changes: 7 additions & 4 deletions frontend/src/pages/users/User.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -274,15 +274,16 @@ const UserComponent: FC<Props> = ({ user, refetch }) => {
});
})
.catch((error: unknown) => {
let message: React.ReactNode | string | undefined = error instanceof Error && isApolloError(error) && error.message;
if (message === 'pending-email-change')
let message: React.ReactNode | string | undefined =
error instanceof Error && isApolloError(error) && error.message;
if (message === "pending-email-change")
message = (
<>
<h5>Pending email change</h5>
<div>Email change already requested. Please try again later.</div>
</>
);
toast({ variant: "danger", content: message });
toast({ variant: "danger", content: message });
});
};

Expand All @@ -308,7 +309,9 @@ const UserComponent: FC<Props> = ({ user, refetch }) => {
</Link>
)}
{isOwner && (
<Button onClick={() => handleChangeEmail()} className="ms-2">Change Email</Button>
<Button onClick={() => handleChangeEmail()} className="ms-2">
Change Email
</Button>
)}
{isAdmin(Auth.user) && (
<>
Expand Down
52 changes: 34 additions & 18 deletions frontend/src/pages/users/UserConfirmChangeEmail.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { FC, useState } from "react";
import { isApolloError } from "@apollo/client";
import { useNavigate } from "react-router-dom";
import { Button, Form, Row, Col } from "react-bootstrap";
import { Button, Form } from "react-bootstrap";

import type { User } from "src/AuthContext";
import { useQueryParams } from "src/hooks";
import { useQueryParams, useToast } from "src/hooks";
import { userHref } from "src/utils";
import { ErrorMessage } from "src/components/fragments";
import Title from "src/components/title";
Expand All @@ -14,42 +14,58 @@ const ConfirmChangeEmail: FC<{ user: User }> = ({ user }) => {
const navigate = useNavigate();
const [submitError, setSubmitError] = useState<string | undefined>();
const [{ token }] = useQueryParams({
token: { name: "token", type: "string" },
token: { name: "key", type: "string" },
});
const toast = useToast();

const [confirmChangeEmail, { loading }] = useConfirmChangeEmail();

if (!token) return <ErrorMessage error="Missing token" />;
if (!token) return <ErrorMessage error="Missing key" />;
if (submitError) return <ErrorMessage error={submitError} />;

const onSubmit = () => {
setSubmitError(undefined);
confirmChangeEmail({ variables: { token } })
.then(() => {
navigate(userHref(user));
.then((res) => {
const status = res.data?.confirmChangeEmail;
if (status === "SUCCESS") {
toast({
variant: "success",
content: (
<>
<h5>Email successfully changed</h5>
</>
),
});
navigate(userHref(user));
} else if (status === "INVALID_TOKEN")
setSubmitError(
"Invalid or expired token, please restart the process."
);
else if (status === "EXPIRED")
setSubmitError(
"Email change token expired, please restart the process."
);
else setSubmitError("An unknown error occurred");
})
.catch(
(error: unknown) =>
error instanceof Error &&
isApolloError(error) &&
setSubmitError(error.message)
);
return false;
};

return (
<div className="LoginPrompt">
<Title page="Confirm Email" />
<Form className="align-self-center col-8 mx-auto" onSubmit={onSubmit}>
<Row>
<Col
xs={{ span: 3, offset: 9 }}
className="justify-content-end mt-2 d-flex"
>
<Button type="submit" disabled={loading}>
Confirm email change
</Button>
</Col>
</Row>
<Title page="Confirm Email change" />
<Form className="align-self-center col-8 mx-auto">
<h5>Confirm change email</h5>
<p>Click the button to confirm email change.</p>
<Button type="submit" disabled={loading} onClick={onSubmit}>
Complete email change
</Button>
</Form>
</div>
);
Expand Down
45 changes: 29 additions & 16 deletions frontend/src/pages/users/UserValidateChangeEmail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,15 +35,33 @@ const ValidateChangeEmail: FC<{ user: User }> = () => {

const [validateChangeEmail, { loading }] = useValidateChangeEmail();

if (submitted) return <div>Submitted!</div>;
if (submitted)
return (
<div className="LoginPrompt">
<div className="align-self-center col-8 mx-auto">
<h5>Confirmation email sent</h5>
<p>Please check your email to complete the email change.</p>
</div>
</div>
);

if (!token) return <ErrorMessage error="Missing token" />;

const onSubmit = (formData: ValidateChangeEmailFormData) => {
setSubmitError(undefined);
validateChangeEmail({ variables: { ...formData } })
.then(() => {
setQueryParam("submitted", true);
.then((res) => {
const status = res.data?.validateChangeEmail;
if (status === "CONFIRM_NEW") setQueryParam("submitted", true);
else if (status === "INVALID_TOKEN")
setSubmitError(
"Invalid or expired token, please restart the process."
);
else if (status === "EXPIRED")
setSubmitError(
"Email change token expired, please restart the process."
);
else setSubmitError("An unknown error occurred");
})
.catch(
(error: unknown) =>
Expand All @@ -66,22 +84,17 @@ const ValidateChangeEmail: FC<{ user: User }> = () => {
className="align-self-center col-8 mx-auto"
onSubmit={handleSubmit(onSubmit)}
>
<h5>Change email</h5>
<p>Enter a new email address to complete email change.</p>
<Form.Control type="hidden" value={token} {...register("token")} />

<Form.Group controlId="email" className="mt-2">
<Row>
<Col xs={4}>
<Form.Label>New Email:</Form.Label>
</Col>
<Col xs={8}>
<Form.Control
className={cx({ "is-invalid": errors?.email })}
type="email"
placeholder="Email"
{...register("email")}
/>
</Col>
</Row>
<Form.Control
className={cx({ "is-invalid": errors?.email })}
type="email"
placeholder="New email"
{...register("email")}
/>
</Form.Group>

{errorList.map((error) => (
Expand Down
8 changes: 4 additions & 4 deletions pkg/email/email.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,11 +54,11 @@ func (m *Manager) Send(email, subject, text, html string) error {

message := mail.NewMsg()
if err := message.FromFormat(config.GetTitle(), config.GetEmailFrom()); err != nil {
return errors.New(fmt.Sprintf("failed to set From address: %s", err))
return fmt.Errorf("failed to set From address: %w", err)
}

if err := message.To(email); err != nil {
return errors.New(fmt.Sprintf("failed to set To address: %s", err))
return fmt.Errorf("failed to set To address: %w", err)
}

message.Subject(subject)
Expand All @@ -68,11 +68,11 @@ func (m *Manager) Send(email, subject, text, html string) error {
client, err := mail.NewClient(config.GetEmailHost(), mail.WithPort(config.GetEmailPort()), mail.WithSMTPAuth(mail.SMTPAuthPlain),
mail.WithUsername(config.GetEmailUser()), mail.WithPassword(config.GetEmailPassword()))
if err != nil {
return errors.New(fmt.Sprintf("failed to create mail client: %s", err))
return fmt.Errorf("failed to create mail client: %w", err)
}

if err := client.DialAndSend(message); err != nil {
return errors.New(fmt.Sprintf("failed to send mail: %s", err))
return fmt.Errorf("failed to send mail: %w", err)
}

// add to email map
Expand Down
10 changes: 1 addition & 9 deletions pkg/models/generated_exec.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion pkg/models/generated_models.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 11 additions & 2 deletions pkg/user/activation.go
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,13 @@ func generateActivationKey(tqb models.UserTokenCreator, email string, inviteKey
Type: models.UserTokenTypeNewUser,
}

activation.SetData(models.NewUserTokenData{
err = activation.SetData(models.NewUserTokenData{
Email: email,
InviteKey: inviteKey,
})
if err != nil {
return nil, err
}

token, err := tqb.Create(activation)
if err != nil {
Expand All @@ -137,6 +140,9 @@ func ActivateNewUser(fac models.Repo, name string, id uuid.UUID, password string
}

data, err := t.GetNewUserTokenData()
if err != nil {
return nil, err
}

if t == nil || t.Type != models.UserTokenTypeNewUser {
return nil, ErrInvalidActivationKey
Expand Down Expand Up @@ -253,9 +259,12 @@ func generateResetPasswordActivationKey(aqb models.UserTokenCreator, userID uuid
Type: models.UserTokenTypeResetPassword,
}

activation.SetData(models.UserTokenData{
err = activation.SetData(models.UserTokenData{
UserID: userID,
})
if err != nil {
return nil, err
}

obj, err := aqb.Create(activation)
if err != nil {
Expand Down
Loading

0 comments on commit 77a9cdb

Please sign in to comment.