Skip to content

Commit

Permalink
Merge pull request #60 from UwUClub/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
Valegox authored Jan 15, 2024
2 parents 24702af + 6588349 commit a4d79c5
Show file tree
Hide file tree
Showing 5 changed files with 85 additions and 36 deletions.
26 changes: 22 additions & 4 deletions api/src/auth/auth.controller.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
import { Body, Controller, Post } from '@nestjs/common';
import { Body, Controller, Post, Headers, UnauthorizedException } from '@nestjs/common';
import { AuthService } from './auth.service';
import { SignInDto } from './_utils/dto/request/sign-in.dto';
import { CreateUserDto } from '../users/_utils/dto/request/create-user.dto';
import { ApiTags } from '@nestjs/swagger';
import { ApiHeader, ApiTags } from '@nestjs/swagger';
import { GoogleLoginDto } from './_utils/dto/request/google-login.dto';
import { UsersService } from '../users/users.service';
import * as jwt from 'jsonwebtoken';
import { ConfigService } from '@nestjs/config';
import { EnvironmentVariables } from '../_utils/config';
import { JwtStrategy } from './jwt/jwt.startegy';

@ApiTags('Auth')
@Controller('auth')
export class AuthController {
constructor(private readonly authService: AuthService) {}
constructor(
private readonly authService: AuthService,
private readonly usersService: UsersService,
private readonly configService: ConfigService<EnvironmentVariables, true>,
private readonly jwtStrategy: JwtStrategy,
) {}

/**
* Endpoint for user login.
Expand All @@ -26,7 +36,15 @@ export class AuthController {
}

@Post('google-login')
googleLogin(@Body() googleLoginDto: GoogleLoginDto) {
async googleLogin(@Headers('Authorization') authorizationHeader: string, @Body() googleLoginDto: GoogleLoginDto) {
if (authorizationHeader) {
const token = authorizationHeader.split(' ')[1];
const decodeToken = jwt.verify(token, this.configService.get('JWT_SECRET'));
if (!decodeToken) throw new UnauthorizedException('Bad token');
const user = await this.jwtStrategy.validate(decodeToken);
console.log(user);
return this.usersService.updateGoogleToken(user, googleLoginDto.accessToken);
}
return this.authService.connectWithGoogle(googleLoginDto);
}
}
38 changes: 34 additions & 4 deletions flutter_area/lib/Core/Manager/google_manager.dart
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import 'dart:convert';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:http/http.dart' as http;

import '../../Utils/constants.dart';
Expand All @@ -7,16 +8,30 @@ import '../Locator/locator.dart';
import 'user_manager.dart';

class GoogleManager {
Future<GoogleSignInAccount?> openGoogleAuthPopup() async {
const List<String> scopes = <String>[
'email',
'https://www.googleapis.com/auth/gmail.addons.current.action.compose',
'https://www.googleapis.com/auth/gmail.compose',
];

final GoogleSignIn googleSignIn = GoogleSignIn(
scopes: scopes,
);
final GoogleSignInAccount? res = await googleSignIn.signIn();
return res;
}

Future<bool> loginWithGoogle(
String accessToken, String completeName, String email) async {
String googleToken, String completeName, String email) async {
final http.Response res = await http.post(
Uri.parse('$kBaseUrl/auth/google-login'),
headers: <String, String>{
'accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8',
},
body: jsonEncode(<String, String>{
'accessToken': accessToken,
'accessToken': googleToken,
'completeName': completeName,
'email': email
}));
Expand All @@ -31,6 +46,23 @@ class GoogleManager {
return false;
}

Future<void> setGoogleToken(String googleToken) async {
final UserManager userManager = locator<UserManager>();
final http.Response res =
await http.post(Uri.parse('$kBaseUrl/users/google-token'),
headers: <String, String>{
'accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8',
'Authorization': 'Bearer ${userManager.accessToken}',
},
body: jsonEncode(<String, String>{'googleToken': googleToken}));
if (res.statusCode != 201) {
return;
}
userManager.isGoogleLogged = googleToken != 'none';
userManager.connectionsViewModel?.notify();
}

Future<bool> createDraft(String name, String email) async {
try {
final UserManager userManager = locator<UserManager>();
Expand All @@ -49,6 +81,4 @@ class GoogleManager {
}
return false;
}

Future signOutFromGoogle() async {}
}
18 changes: 15 additions & 3 deletions flutter_area/lib/UI/Connections/connections_view.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:provider/provider.dart';

import '../../Core/Locator/locator.dart';
Expand Down Expand Up @@ -96,10 +97,21 @@ class _ConnectionsViewState extends State<ConnectionsView> {
? AppLocalizations.of(context)!.logout
: AppLocalizations.of(context)!.connect,
onPressed: () async {
if (userManager.isGithubLogged!) {
await googleManager.signOutFromGoogle();
if (userManager.isGoogleLogged!) {
await googleManager.setGoogleToken('none');
} else {
// todo connect to google
final GoogleSignInAccount? res =
await googleManager.openGoogleAuthPopup();
if (res == null) {
return;
}
final GoogleSignInAuthentication googleToken =
await res.authentication;
if (googleToken.accessToken == null) {
return;
}
googleManager
.setGoogleToken(googleToken.accessToken!);
}
},
),
Expand Down
37 changes: 13 additions & 24 deletions flutter_area/lib/UI/Login/google_button.dart
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import '../../Core/Locator/locator.dart';
import '../../Core/Manager/google_manager.dart';
import '../../Utils/Extensions/color_extensions.dart';
import '../../Utils/Extensions/double_extensions.dart';
import '../../Utils/mk_print.dart';

class GoogleButton extends StatelessWidget {
const GoogleButton({
Expand All @@ -16,30 +15,20 @@ class GoogleButton extends StatelessWidget {
Future<void> loginWithGoogle(BuildContext context) async {
final GoogleManager googleManager = locator<GoogleManager>();

const List<String> scopes = <String>[
'email',
'https://www.googleapis.com/auth/gmail.addons.current.action.compose',
'https://www.googleapis.com/auth/gmail.compose',
];

final GoogleSignIn googleSignIn = GoogleSignIn(
scopes: scopes,
);
final GoogleSignInAccount? res = await googleManager.openGoogleAuthPopup();
if (res == null) {
return;
}

try {
final GoogleSignInAccount? res = await googleSignIn.signIn();
final GoogleSignInAuthentication token = await res!.authentication;
if (token.accessToken == null || res.displayName == null) {
return;
}
final bool success = await googleManager.loginWithGoogle(
token.accessToken!, res.displayName!, res.email);
if (success) {
// ignore: use_build_context_synchronously
Navigator.of(context).pushNamed('/home');
}
} catch (error) {
mkPrint(error);
final GoogleSignInAuthentication token = await res.authentication;
if (token.accessToken == null || res.displayName == null) {
return;
}
final bool success = await googleManager.loginWithGoogle(
token.accessToken!, res.displayName!, res.email);
if (success) {
// ignore: use_build_context_synchronously
Navigator.of(context).pushNamed('/home');
}
}

Expand Down
2 changes: 1 addition & 1 deletion flutter_area/lib/UI/Profile/profile_view.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class _ProfileViewState extends State<ProfileView> {
onPressed: () async {
await userManager.logout();
// ignore: use_build_context_synchronously
Navigator.of(context).pushNamed('/');
Navigator.of(context).pop();
})
]),
],
Expand Down

0 comments on commit a4d79c5

Please sign in to comment.