Skip to content

Commit cf3e814

Browse files
Added avatar icon on sign in
1 parent 6cb6f1b commit cf3e814

File tree

7 files changed

+92
-46
lines changed

7 files changed

+92
-46
lines changed

client/src/actions/index.js

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,19 @@ import {
1111
PAYMENT_RESPONSE, CART_TOTAL, HANDLE_SIGN_UP_RESET,
1212
} from './types';
1313
import {INTERNAL_SERVER_ERROR_CODE, BAD_REQUEST_ERROR_CODE} from '../constants/http_error_codes'
14-
import {SHOPPERS_PRODUCT_INFO_COOKIE, CART_TOTAL_COOKIE, TOKEN_ID_COOKIE} from '../constants/cookies'
14+
import {SHOPPERS_PRODUCT_INFO_COOKIE, CART_TOTAL_COOKIE, AUTH_DETAILS_COOKIE} from '../constants/cookies'
1515
import history from "../history";
1616
import {Base64} from 'js-base64';
1717
import Cookies from 'js-cookie';
1818
import log from "loglevel";
1919
import {commonServiceAPI, authServiceAPI} from "../api/service_api";
2020
import axios from 'axios';
2121

22-
export const setTokenFromCookie = tokenId => {
23-
log.info(`[ACTION]: setTokenFromCookie tokenId = ${tokenId}`)
22+
export const setAuthDetailsFromCookie = savedResponse => {
23+
log.info(`[ACTION]: setTokenFromCookie savedResponse = ${savedResponse}`)
2424
return {
2525
type: HANDLE_SIGN_IN,
26-
payload: tokenId
26+
payload: savedResponse
2727
}
2828
}
2929

@@ -57,8 +57,8 @@ export const signIn = formValues => async (dispatch) => {
5757
if (response) {
5858
if (response.data.jwt) {
5959
log.info(`[ACTION]: dispatch HANDLE_SIGN_IN response.data.jwt = ${response.data.jwt}`)
60-
dispatch({type: HANDLE_SIGN_IN, payload: response.data.jwt});
61-
Cookies.set(TOKEN_ID_COOKIE, response.data.jwt, {expires: 2});
60+
dispatch({type: HANDLE_SIGN_IN, payload: response.data});
61+
Cookies.set(AUTH_DETAILS_COOKIE, response.data, {expires: 2});
6262
history.push('/');
6363
} else {
6464
log.info(`[ACTION]: dispatch HANDLE_SIGN_IN_ERROR response.data.error = ${response.data.error}`)
@@ -69,7 +69,7 @@ export const signIn = formValues => async (dispatch) => {
6969

7070
export const signOut = () => {
7171
log.info(`[ACTION]: signOut Cookie is removed...`)
72-
Cookies.remove(TOKEN_ID_COOKIE)
72+
Cookies.remove(AUTH_DETAILS_COOKIE)
7373
return {
7474
type: HANDLE_SIGN_OUT
7575
}

client/src/components/routes/navbar/navBar.js

Lines changed: 64 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {Menu, Grid} from '@material-ui/core';
88
import MenuIcon from '@material-ui/icons/Menu';
99
import MoreIcon from '@material-ui/icons/MoreVert';
1010
import Cookies from 'js-cookie';
11-
import {getDataViaAPI, setTokenFromCookie, signOut} from '../../../actions';
11+
import {getDataViaAPI, setAuthDetailsFromCookie, signOut} from '../../../actions';
1212
import {connect, useDispatch} from 'react-redux'
1313

1414
import {
@@ -29,18 +29,21 @@ import {HTTPError} from "../../ui/error/httpError";
2929
import {BadRequest} from "../../ui/error/badRequest";
3030
import SearchBar from "./searchBar";
3131
import SideBar from "./sideBar";
32-
import {SHOPPERS_PRODUCT_INFO_COOKIE, TOKEN_ID_COOKIE} from "../../../constants/cookies";
32+
import {SHOPPERS_PRODUCT_INFO_COOKIE, AUTH_DETAILS_COOKIE} from "../../../constants/cookies";
3333
import {TABS_DATA_API} from "../../../constants/api_routes";
3434
import {TABS_API_OBJECT_LEN} from "../../../constants/constants"
35+
import Avatar from '@material-ui/core/Avatar';
36+
import history from "../../../history";
3537

3638
const NavBar = props => {
3739
const classes = useNavBarStyles();
3840
const [anchorEl, setAnchorEl] = React.useState(null);
3941
const [mobileSearchState, setMobileSearchState] = React.useState(false);
4042
const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = React.useState(null);
4143
const [hamburgerBtnState, setHamburgerBtnState] = React.useState(false);
42-
const {isSignedIn, tokenId} = useSelector(state => state.signInReducer)
44+
const {isSignedIn, tokenId, firstName} = useSelector(state => state.signInReducer)
4345
const tabsAPIData = useSelector(state => state.tabsDataReducer)
46+
const addToCart = useSelector(state => state.addToCartReducer)
4447

4548
const isMenuOpen = Boolean(anchorEl);
4649
const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);
@@ -79,15 +82,15 @@ const NavBar = props => {
7982
// account details from the cookie.
8083
if (isSignedIn === null) {
8184
log.info(`[NavBar]: isSignedIn is null`)
82-
let tokenIdFromCookie = Cookies.get(TOKEN_ID_COOKIE)
83-
if (tokenIdFromCookie) {
84-
log.info(`[NavBar]: Token set from Cookie`)
85-
props.setTokenFromCookie(tokenIdFromCookie)
85+
let savedAuthDetails = Cookies.get(AUTH_DETAILS_COOKIE)
86+
if (savedAuthDetails) {
87+
log.info(`[NavBar]: setting Auth Details from Cookie`)
88+
props.setAuthDetailsFromCookie(JSON.parse(savedAuthDetails))
8689
}
8790
}
8891

8992
// tabs data is not loaded then load it.
90-
if(!tabsAPIData.hasOwnProperty("data")) {
93+
if (!tabsAPIData.hasOwnProperty("data")) {
9194
props.getDataViaAPI(LOAD_TABS_DATA, TABS_DATA_API)
9295
}
9396

@@ -155,13 +158,35 @@ const NavBar = props => {
155158
open={isMenuOpen}
156159
onClose={handleMenuClose}
157160
>
158-
<Link to={!tokenId ? "/signin" : "/"}>
159-
<MenuItem onClick={handleLoginStatus}>{!tokenId ? 'SignIn' : 'SignOut'}</MenuItem>
161+
<Link to={isSignedIn ? "/" : "/signin"}>
162+
<MenuItem onClick={handleLoginStatus}>{isSignedIn ? 'Sign Out' : 'Sign In'}</MenuItem>
160163
</Link>
161164
<MenuItem onClick={handleMenuClose}>My account</MenuItem>
162165
</Menu>
163166
);
164167

168+
const menuProfileBtnHandler = () => {
169+
if (isSignedIn) {
170+
history.push("/")
171+
} else {
172+
history.push("/signin")
173+
}
174+
setMobileMoreAnchorEl(null);
175+
}
176+
177+
const menuBagBtnHandler = () => {
178+
history.push("/shopping-bag")
179+
setMobileMoreAnchorEl(null);
180+
}
181+
182+
const renderAvatar = () => {
183+
return (
184+
<Avatar className={classes.orange} sizes="small"
185+
style={{width: 20, height: 20, marginBottom: 3}}>{firstName? firstName.charAt(0):
186+
"S"}</Avatar>
187+
)
188+
}
189+
165190
const mobileMenuId = 'primary-search-account-menu-mobile';
166191
const renderMobileMenu = (
167192
<Menu
@@ -173,35 +198,43 @@ const NavBar = props => {
173198
open={isMobileMenuOpen}
174199
onClose={handleMobileMenuClose}
175200
>
176-
<MenuItem onClick={handleProfileMenuOpen}>
177-
<IconButton
178-
aria-label="account of current user"
179-
aria-controls="primary-search-account-menu"
180-
aria-haspopup="true"
181-
color="inherit"
182-
>
183-
<AccountCircle/>
184-
</IconButton>
185-
<p>Login</p>
201+
<MenuItem onClick={menuProfileBtnHandler} style={{padding: "0 0.7rem 0 0"}}>
202+
<Grid container alignItems="center">
203+
<Grid item>
204+
<IconButton aria-label="account of current user"
205+
aria-controls="primary-search-account-menu"
206+
aria-haspopup="true"
207+
color="inherit">
208+
{isSignedIn ? renderAvatar() : <AccountCircle/>}
209+
</IconButton>
210+
</Grid>
211+
<Grid item>
212+
<p>{isSignedIn ? 'Sign Out' : 'Sign In'}</p>
213+
</Grid>
214+
</Grid>
186215
</MenuItem>
187-
<MenuItem>
188-
<IconButton aria-label="show 11 new notifications" color="inherit">
189-
<Badge badgeContent={11} color="secondary">
190-
<LocalMallIcon/>
191-
</Badge>
192-
</IconButton>
193-
<p>Bag</p>
216+
<MenuItem onClick={menuBagBtnHandler} style={{padding: "0 0.7rem 0 0"}}>
217+
<Grid container alignItems="center">
218+
<Grid item xs={7}>
219+
<IconButton color="inherit">
220+
<Badge badgeContent={addToCart.totalQuantity} color="secondary">
221+
<LocalMallIcon/>
222+
</Badge>
223+
</IconButton>
224+
</Grid>
225+
<Grid item>
226+
<p>Bag</p>
227+
</Grid>
228+
</Grid>
194229
</MenuItem>
195230
</Menu>
196231
);
197232

198233
const handleMobileSearchOpen = () => {
199-
log.info("Mobile Search is clicked....")
200234
setMobileSearchState(true)
201235
}
202236

203237
const handleMobileSearchClose = () => {
204-
log.info("Mobile Search is clicked....")
205238
setMobileSearchState(false)
206239
}
207240

@@ -280,7 +313,7 @@ const NavBar = props => {
280313
<Box display="flex" justifyContent="center" alignItems="center" css={{width: 90}}>
281314
<Box width="50%" onClick={handleProfileMenuOpen} css={{cursor: 'pointer'}}>
282315
<Box pl={1} pt={0.3}>
283-
<AccountCircle/>
316+
{isSignedIn ? renderAvatar() : <AccountCircle/>}
284317
</Box>
285318
<Box style={{color: "black", fontSize: "0.8rem", fontWeight: 'bold'}}>
286319
Profile
@@ -321,4 +354,4 @@ const NavBar = props => {
321354
);
322355
};
323356

324-
export default connect(null, {setTokenFromCookie, signOut, getDataViaAPI})(NavBar);
357+
export default connect(null, {setAuthDetailsFromCookie, signOut, getDataViaAPI})(NavBar);

client/src/constants/cookies.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,3 @@
1-
export const TOKEN_ID_COOKIE = "TOKEN_ID_COOKIE";
1+
export const AUTH_DETAILS_COOKIE = "AUTH_DETAILS_COOKIE";
22
export const SHOPPERS_PRODUCT_INFO_COOKIE = 'SHOPPERS_PRODUCT_INFO_COOKIE';
33
export const CART_TOTAL_COOKIE = "CART_TOTAL_COOKIE";

client/src/reducers/screens/commonScreenReducer.js

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,17 +30,20 @@ import {
3030
import _ from "lodash";
3131

3232

33-
export const signInReducer = (state = {isSignedIn: null, timestamp: null}, action) => {
33+
export const signInReducer = (state
34+
= {isSignedIn: null, timestamp: null, firstName: null}, action) => {
3435

3536
// timestamp is used to update the state so that
3637
// we can stop loading progress component
3738
switch (action.type) {
3839
case HANDLE_SIGN_IN:
39-
return {...state, isSignedIn: true, tokenId: action.payload, timestamp: Date.now()};
40+
return {...state, isSignedIn: true, tokenId: action.payload.jwt,
41+
firstName: action.payload.firstName, timestamp: Date.now()};
4042
case HANDLE_SIGN_IN_ERROR:
4143
return {...state, isSignedIn: false, errorMsg: action.payload, timestamp: Date.now()};
4244
case HANDLE_SIGN_OUT:
43-
return _.omit(state, 'tokenId', 'errorMsg');
45+
_.omit(state, 'tokenId', 'errorMsg')
46+
return {...state, isSignedIn: false};
4447
default:
4548
return state;
4649
}

client/src/styles/materialUI/navBarStyles.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import {fade, makeStyles} from "@material-ui/core/styles";
2+
import deepOrange from "@material-ui/core/colors/deepOrange";
23

34
const useNavBarStyles = makeStyles(theme => ({
45
grow_1: {
@@ -155,7 +156,11 @@ const useNavBarStyles = makeStyles(theme => ({
155156
},
156157
mobileSearchButton: {
157158
alignSelf: "flex-end"
158-
}
159+
},
160+
orange: {
161+
color: theme.palette.getContrastText(deepOrange[500]),
162+
backgroundColor: deepOrange[500],
163+
},
159164
}));
160165

161166
export default useNavBarStyles;

server/authentication-service/src/main/java/com/ujjaval/ecommerce/authenticationservice/controller/AuthController.java

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,15 +90,19 @@ public ResponseEntity<?> createAuthenticationToken(
9090
Md5Util.getInstance().getMd5Hash(authenticationRequest.getPassword()))
9191
);
9292
} catch (BadCredentialsException e) {
93-
return ResponseEntity.ok(new AuthenticationResponse(null, "Incorrect username or password."));
93+
return ResponseEntity.ok(new AuthenticationResponse(null, "Incorrect username or password.",
94+
null));
9495
} catch (Exception e) {
95-
return ResponseEntity.ok(new AuthenticationResponse(null, "Username does not exist."));
96+
return ResponseEntity.ok(new AuthenticationResponse(null, "Username does not exist.",
97+
null));
9698
}
9799

98100
final UserDetails userDetails = customUserDetailsService.loadUserByUsername(authenticationRequest.getUsername());
99101

100102
final String jwt = jwtTokenUtil.generateToken(userDetails);
101103

102-
return ResponseEntity.ok(new AuthenticationResponse(jwt, null));
104+
UserInfo userInfo = authDataService.findByUsername(authenticationRequest.getUsername());
105+
106+
return ResponseEntity.ok(new AuthenticationResponse(jwt, null, userInfo.getFirstName()));
103107
}
104108
}

server/authentication-service/src/main/java/com/ujjaval/ecommerce/authenticationservice/model/AuthenticationResponse.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ public class AuthenticationResponse {
1111

1212
private String jwt;
1313
private String error;
14+
private String firstName;
1415
}

0 commit comments

Comments
 (0)