Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement change password in user profile #664

Merged
merged 2 commits into from
Nov 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .github/workflows/lint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ jobs:
- uses: actions/setup-python@v4
with:
python-version: '3.10'
- run: |
sudo apt-get update
sudo apt-get install pkg-config libxml2-dev libxmlsec1-dev libxmlsec1-openssl
- run: pip install -Ur mypy-requirements.txt
- run: mypy .

Expand Down
36 changes: 36 additions & 0 deletions assets/auth/firebase/change_password.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import {auth} from './init';
import {signInWithEmailAndPassword, updatePassword, AuthError} from 'firebase/auth';

declare const firebaseUserEmail : string;

const form = document.getElementById('formChangePassword') as HTMLFormElement;
const firebaseStatus = document.getElementById('firebase-status') as HTMLInputElement;

if (form != null) {
form.onsubmit = (event) => {
event.preventDefault();

const data = new FormData(form);
const oldPassword = data.get('old_password') as string;
const newPassword = data.get('new_password') as string;
const newPassword2 = data.get('new_password2') as string;

if (newPassword !== newPassword2) {
form.submit();
return;
}

signInWithEmailAndPassword(auth, firebaseUserEmail, oldPassword).then((userCredential) => {
MarkLark86 marked this conversation as resolved.
Show resolved Hide resolved
return updatePassword(userCredential.user, newPassword).then(() => {
firebaseStatus.value = 'OK';
form.submit();
});
}).catch((reason: AuthError) => {
firebaseStatus.value = reason.code;
form.submit();
});

return false;
};
}

12 changes: 12 additions & 0 deletions assets/auth/firebase/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import {getAuth} from 'firebase/auth';
import {initializeApp} from 'firebase/app';

declare const firebaseConfig : {
apiKey: string;
authDomain: string;
projectId: string;
messagingSenderId: string;
};

export const app = initializeApp(firebaseConfig);
export const auth = getAuth();
52 changes: 52 additions & 0 deletions assets/auth/firebase/login.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import {auth} from './init';
import {signInWithEmailAndPassword, signOut} from 'firebase/auth';

const form = document.getElementById('formLogin') as HTMLFormElement;
const params = new URLSearchParams(window.location.search);

if (params.get('email')) {
form['email'].value = params.get('email');
}

const sendTokenToServer = (token: string) => {
window.location.replace(`/firebase_auth_token?token=${token}`);
};

// check firebase auth status
auth.onAuthStateChanged((user) => {
if (user != null) { // there is a firebase user authenticated
if (params.get('user_error') === '1') { // but missing in newshub
return;
}

if (params.get('logout') === '1') { // force logout from firebase
signOut(auth);
return;
}

const tokenError = params.get('token_error');

user.getIdToken(tokenError === '1').then(sendTokenToServer);
}
});

// override submit form action to authenticate using firebase
// and fallback to newshub when credentials are invalid
form.onsubmit = (event) => {
event.preventDefault();

const data = new FormData(form);
const email = data.get('email') as string;
const password = data.get('password') as string;

signInWithEmailAndPassword(auth, email, password).then((userCredential) => {
userCredential.user.getIdToken().then(sendTokenToServer);
}, (reason) => {
// login via firebase didn't work out,
// try standard newshub login
console.error(reason);
form.submit();
});

return false;
};
42 changes: 42 additions & 0 deletions assets/auth/firebase/reset_password.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {auth} from './init';
import {sendPasswordResetEmail} from 'firebase/auth';

declare const nextUrl: string;

const form = document.getElementById('formToken') as HTMLFormElement;
const url = new URL(nextUrl);
const params = new URLSearchParams(url.search);
const sendButton = document.getElementById('reset-password-btn') as HTMLButtonElement;

if (sendButton != null) {
form.onsubmit = (event) => {
event.preventDefault();

if (sendButton.disabled) {
return false;
}

const data = new FormData(form);
const email = data.get('email') as string;

params.append('email', email);
url.search = params.toString();

sendButton.disabled = true;
sendPasswordResetEmail(auth, email, {url: url.toString()})
.then(() => {
form.submit();
})
.catch((reason) => {
if (reason.code === 'auth/user-not-found') {
// User not registered with OAuth, try attempting normal password reset
form.submit();
} else {
console.error(reason);
sendButton.disabled = false; // allow another request if there was an error
}
});

return false;
};
}
2 changes: 1 addition & 1 deletion assets/companies/components/EditCompany.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ class EditCompany extends React.Component<IProps, IState> {
onChange={this.props.onChange}
save={this.save}
deleteCompany={this.deleteCompany}
ssoEnabled={this.props.ssoEnabled && currentAuthProvider?.auth_type === 'saml'}
ssoEnabled={this.props.ssoEnabled && currentAuthProvider?.auth_type !== 'password'}
authProviders={this.props.authProviders}
countries = {this.props.countries}
/>
Expand Down
10 changes: 9 additions & 1 deletion assets/components/CheckboxInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,16 @@ import React from 'react';
import classNames from 'classnames';
import PropTypes from 'prop-types';

interface IProps {
name?: string;
label: string;
readOnly?: boolean;
labelClass?: string;
value?: boolean;
onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
}

function CheckboxInput({name, label, onChange, value, labelClass, readOnly}: any) {
function CheckboxInput({name, label, onChange, value, labelClass, readOnly}: IProps) {
if (!name) {
name = `input-${label}`;
}
Expand Down
37 changes: 30 additions & 7 deletions assets/components/TextInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,45 @@ import InputWrapper from './InputWrapper';

import {gettext} from 'utils';

interface IProps {
type?: string;
name: string;
label?: string;
labelClasses? : string;
value?: string;
copyAction?: boolean;
error?: string[] | null;
required?: boolean;
maxLength?: number;
placeholder?: string;
description?: string;
min?: number;
autoFocus?: boolean;
readOnly?: boolean;
onChange?: React.ChangeEventHandler<HTMLInputElement>;
onKeyDown?: React.KeyboardEventHandler<HTMLInputElement>;
props?: {[key: string]: any};
}

function TextInput({
type,
name,
label,
labelClasses,
onChange,
value,
error,
required,
readOnly,
onChange,
maxLength,
placeholder,
description,
min,
autoFocus,
copyAction,
onKeyDown,
...props
}: any) {
}: IProps) {
return (
<InputWrapper error={error} name={name} testId={`field-${name}`}>
{label && (
Expand All @@ -31,8 +52,11 @@ function TextInput({
{copyAction &&
<button
className='icon-button'
onClick={(e: any) => {e.preventDefault();navigator.clipboard.writeText(value);}}
title={gettext('Copy')}
onClick={(e) => {
e.preventDefault();
navigator.clipboard.writeText(value || '');
}}
>
<i className='icon--copy'></i>
</button>
Expand All @@ -45,13 +69,14 @@ function TextInput({
name={name}
className="form-control"
value={value}
onChange={onChange}
onChange={readOnly === true ? undefined : onChange}
required={required}
maxLength={maxLength}
disabled={readOnly}
placeholder={placeholder}
min={min}
autoFocus={autoFocus}
onKeyDown={onKeyDown}
{...props}
/>
{error && <div className="alert alert-danger">{error}</div>}
Expand Down Expand Up @@ -81,6 +106,4 @@ TextInput.propTypes = {

TextInput.defaultProps = {autoFocus: false};

const component: React.ComponentType<any> = TextInput;

export default component;
export default TextInput;
2 changes: 1 addition & 1 deletion assets/components/TextListInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ class TextListInput extends React.Component<any, any> {
{!readOnly && <TextInput
name={name}
onChange={this.inputChange}
onKeyDown={(event: any) => {
onKeyDown={(event) => {
if (event.keyCode === KEYCODES.ENTER ||
event.keyCode === KEYCODES.DOWN) {
event.preventDefault();
Expand Down
3 changes: 3 additions & 0 deletions assets/interfaces/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,3 +44,6 @@ export interface IUser {
last_run_time?: TDatetime;
};
}

type IUserProfileEditable = Pick<IUser, 'first_name' | 'last_name' | 'phone' | 'mobile' | 'role' | 'locale' | 'receive_email' | 'receive_app_notifications'>;
export type IUserProfileUpdates = Partial<IUserProfileEditable>;
19 changes: 13 additions & 6 deletions assets/reducers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,14 @@ import {REMOVE_NEW_ITEMS, SET_NEW_ITEM} from './agenda/actions';
import {SET_ERROR_MESSAGE, toggleValue} from 'utils';
import {topicsReducer} from './topics/reducer';

export function modalReducer(state?: any, action?: any): any {
export interface IModalState {
modal: string;
data: any;
modalProps: any;
formValid?: boolean;
}

export function modalReducer(state?: IModalState, action?: any): IModalState | undefined {
if (!action) {
return state;
}
Expand All @@ -54,19 +61,19 @@ export function modalReducer(state?: any, action?: any): any {
};

case CLOSE_MODAL:
return null;
return undefined;

case MODAL_FORM_VALID:
return {
return state ? {
...state,
formValid: true,
};
} : state;

case MODAL_FORM_INVALID:
return {
return state ? {
...state,
formValid: false,
};
} : state;

default:
return state;
Expand Down
7 changes: 4 additions & 3 deletions assets/user-profile/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {store as userProfileStore} from './store';
import {getLocale} from '../utils';
import {reloadMyTopics as reloadMyAgendaTopics} from '../agenda/actions';
import {reloadMyTopics as reloadMyWireTopics} from '../wire/actions';
import {IUserProfileUpdates} from 'interfaces/user';

export const GET_TOPICS = 'GET_TOPICS';
export function getTopics(topics: any) {
Expand All @@ -19,8 +20,8 @@ export function getUser(user: any) {
}

export const EDIT_USER = 'EDIT_USER';
export function editUser(event: any) {
return {type: EDIT_USER, event};
export function editUser(payload: IUserProfileUpdates) {
return {type: EDIT_USER, payload};
}

export const INIT_DATA = 'INIT_DATA';
Expand Down Expand Up @@ -299,7 +300,7 @@ export function fetchFolders() {
const userTopicsUrl = getFoldersUrl(state, false);

return Promise.all([
state.company !== 'None' ? server.get(companyTopicsUrl).then(({_items}: {_items: Array<any>}) => _items) : Promise.resolve([]),
state.company ? server.get(companyTopicsUrl).then(({_items}: {_items: Array<any>}) => _items) : Promise.resolve([]),
server.get(userTopicsUrl).then(({_items}: {_items: Array<any>}) => _items),
]).then(([companyFolders, userFolders]) => {
dispatch({
Expand Down
Loading