I'm trying to keep users logged in with nestjs backend, when I use Postman the process works very smoothly, but with Flutter I don't know how to do it. I don't think that I actually understand how sessions work for mobiles, I tried looking for some proper explaining but I couldn't find anything so far.
Nestjs Code
@Controller('users')
@Serialize(UserDto)
export class UsersController {
constructor(
private usersService: UsersService,
private authService: AuthService,
) {}
@Get('/whoami')
@UseGuards(AuthGuard)
whoAmI(@currentUser() user: User) {
return user;
}
@Get()
getUsers(@Query('email') email: string) {
return this.usersService.find(email);
}
@Post('/signup')
async sendUser(@Body() body: UserDto, @Session() session: any) {
console.log(body);
const user = await this.authService.signup(body.email, body.password);
session.userId = user.id;
console.log(session.userId);
return user;
}
@Post('/signin')
async signin(@Body() body: UserDto, @Session() session: any) {
const user = await this.authService.signin(body.email, body.password);
session.userId = user.id;
console.log(session.userId);
return user;
}
@Post('/signout')
async signout(@Session() session: any) {
console.log(session.userId);
if (!session.userId) {
throw new NotFoundException('user not found');
}
session.userId = null;
}
}
Flutter Code
Future<void> signin(
String username, String password, BuildContext context) async {
try {
var url = 'https://example-app.herokuapp.com/users/signin';
var dio = Dio();
var response =
await dio.post(url, data: {'email': username, 'password': password}, options: Options(headers: {'Accept': 'application/json'}));
print(response.headers);
// response;
Navigator.of(context).pushNamed(CategoryDetailScreen.routeName);
} catch (err) {
print(err);
throw err;
}
}
Future<void> signout() async {
try {
var url = 'https://example-app.herokuapp.com/users/signout';
var dio = Dio();
var response = await dio.post(url,
options: Options(headers: {
'cookie':
'key'
}
)
);
print(response.headers);
response;
// return response;
} catch (err) {
print(err);
throw err;
}
}