Commit 1c9c558e authored by saliou673's avatar saliou673
Browse files

store logged user info in the cache

parent 4ca625fa
...@@ -31,16 +31,12 @@ public class PostController { ...@@ -31,16 +31,12 @@ public class PostController {
private final UserService userService; private final UserService userService;
private final ObjectMapper mapper = new ObjectMapper(); private final ObjectMapper mapper = new ObjectMapper();
@PostMapping("/add/{userid}") @PostMapping("/{userid}")
public ResponseEntity<Post> add(@RequestBody JsonNode jsonNode, @PathVariable String userid) { public ResponseEntity<Post> add(@RequestBody PostEntity post, @PathVariable String userid) {
User author = userService.getById(userid); User author = userService.getById(userid);
Post post = mapper.convertValue(jsonNode, PostEntity.class);
post.setAuthor(author); post.setAuthor(author);
post.setDate(DateGenerator.generateDate());
post.setComments(new ArrayList<>());
postService.add(post); postService.add(post);
return new ResponseEntity<>(post, HttpStatus.CREATED); return new ResponseEntity<>(post, HttpStatus.CREATED);
......
...@@ -12,10 +12,12 @@ import org.slf4j.LoggerFactory; ...@@ -12,10 +12,12 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.lang.Nullable;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List; import java.util.List;
@RestController @RestController
...@@ -67,7 +69,16 @@ public class UserController { ...@@ -67,7 +69,16 @@ public class UserController {
} }
@GetMapping() @GetMapping()
public ResponseEntity<List<User>> getAllUsers() { public ResponseEntity<List<User>> getAllUsers(@RequestParam @Nullable String username) {
if (username != null && !username.isEmpty()) {
System.out.println("i'm inside");
var user = userService.getByUsername(username);
List<User> users = new ArrayList<>();
if (user != null) {
users.add(user);
}
return new ResponseEntity<>(users, HttpStatus.OK);
}
return new ResponseEntity<>(userService.findAll(), HttpStatus.OK); return new ResponseEntity<>(userService.findAll(), HttpStatus.OK);
} }
......
...@@ -7,6 +7,8 @@ import org.springframework.data.annotation.Id; ...@@ -7,6 +7,8 @@ import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field; import org.springframework.data.mongodb.core.mapping.Field;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
...@@ -36,7 +38,7 @@ public class PostEntity implements Post{ ...@@ -36,7 +38,7 @@ public class PostEntity implements Post{
this.subject = subject; this.subject = subject;
this.content = content; this.content = content;
this.author = null; this.author = null;
this.date = null; this.date = Timestamp.valueOf(LocalDateTime.now()).toString();
this.comments = new ArrayList<>(); this.comments = new ArrayList<>();
} }
......
...@@ -6,6 +6,8 @@ import com.example.server.model.user.UserEntity; ...@@ -6,6 +6,8 @@ import com.example.server.model.user.UserEntity;
import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository; import org.springframework.stereotype.Repository;
import java.util.List;
@Repository @Repository
public interface UserRepository extends MongoRepository<User, String> { public interface UserRepository extends MongoRepository<User, String> {
...@@ -14,5 +16,5 @@ public interface UserRepository extends MongoRepository<User, String> { ...@@ -14,5 +16,5 @@ public interface UserRepository extends MongoRepository<User, String> {
UserEntity getUserById(String id); UserEntity getUserById(String id);
UserEntity findByUserName(String userName); List<UserEntity> findByUserName(String userName);
} }
...@@ -17,7 +17,11 @@ public class CustomUserDetailsService implements UserDetailsService { ...@@ -17,7 +17,11 @@ public class CustomUserDetailsService implements UserDetailsService {
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = repository.findByUserName(username); var list= repository.findByUserName(username);
User user = null;
if (list.size() > 0) {
user = list.get(0);
}
return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), new ArrayList<>()); return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), new ArrayList<>());
} }
} }
...@@ -59,6 +59,11 @@ public class UserServiceImplement implements UserService{ ...@@ -59,6 +59,11 @@ public class UserServiceImplement implements UserService{
@Override @Override
public UserEntity getByUsername(String username) { public UserEntity getByUsername(String username) {
return repository.findByUserName(username); var list= repository.findByUserName(username);
UserEntity user = null;
if (list.size() > 0) {
user = list.get(0);
}
return user;
} }
} }
...@@ -6,12 +6,14 @@ import { MessagetestComponent } from './messagetest/messagetest.component'; ...@@ -6,12 +6,14 @@ import { MessagetestComponent } from './messagetest/messagetest.component';
import { NotfoundComponent } from './notfound/notfound.component'; import { NotfoundComponent } from './notfound/notfound.component';
import { PostDetailsComponent } from './post-details/post-details.component'; import { PostDetailsComponent } from './post-details/post-details.component';
import { SignupComponent } from './signup/signup.component'; import { SignupComponent } from './signup/signup.component';
import { CreatePostComponent } from './create-post/create-post.component'
const routes: Routes = [ const routes: Routes = [
{ path: 'home', component: HomeComponent }, { path: 'home', component: HomeComponent },
{ path: 'test', component: MessagetestComponent }, { path: 'test', component: MessagetestComponent },
{ path: 'login', component: LoginComponent}, { path: 'login', component: LoginComponent},
{ path: 'signup', component: SignupComponent}, { path: 'signup', component: SignupComponent},
{ path: 'posts/create', component: CreatePostComponent},
{ path: 'posts/:id', component: PostDetailsComponent}, { path: 'posts/:id', component: PostDetailsComponent},
{ path: '404', component: NotfoundComponent}, { path: '404', component: NotfoundComponent},
{ path: '', redirectTo: '/home', pathMatch: 'full' }, { path: '', redirectTo: '/home', pathMatch: 'full' },
......
...@@ -22,6 +22,7 @@ import {JwtClientService} from "./services/jwt-client.service"; ...@@ -22,6 +22,7 @@ import {JwtClientService} from "./services/jwt-client.service";
import {CookieService} from 'ngx-cookie-service'; import {CookieService} from 'ngx-cookie-service';
import {SignoutComponent} from './signout/signout.component'; import {SignoutComponent} from './signout/signout.component';
import {httpInterceptorProviders} from "./services"; import {httpInterceptorProviders} from "./services";
import { CreatePostComponent } from './create-post/create-post.component';
@NgModule({ @NgModule({
declarations: [ declarations: [
...@@ -37,7 +38,8 @@ import {httpInterceptorProviders} from "./services"; ...@@ -37,7 +38,8 @@ import {httpInterceptorProviders} from "./services";
SignupComponent, SignupComponent,
QuestionComponent, QuestionComponent,
PostDetailsComponent, PostDetailsComponent,
SignoutComponent SignoutComponent,
CreatePostComponent
], ],
imports: [ imports: [
HttpClientModule, HttpClientModule,
......
<div class="container">
<div class="row">
<div class="col-md-9">
<div class="comment289-box">
<h3>Créer un post</h3>
<hr>
<div class="row">
<form class="form" #f="ngForm" (ngSubmit)="submit(f)" novalidate>
<div class="col-12">
<div class="form-group">
<p>Titre*</p>
<input type="text"
class="form-control name-box24894 input238-design"
placeholder="Titre"
name="subject"
ngModel #subject="ngModel">
</div>
</div>
<div class="col-12">
<div class="form-group">
<textarea
class="form-control"
name="content"
id="content"
cols="30"
rows="10"
ngModel #content="ngModel">
</textarea>
</div>
<button type="button" class="pos393-submit">Publier</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
\ No newline at end of file
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { CreatePostComponent } from './create-post.component';
describe('CreatePostComponent', () => {
let component: CreatePostComponent;
let fixture: ComponentFixture<CreatePostComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ CreatePostComponent ]
})
.compileComponents();
});
beforeEach(() => {
fixture = TestBed.createComponent(CreatePostComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
import { Component, OnInit } from '@angular/core';
import { ToastrService } from 'ngx-toastr';
import { NgForm } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Router } from '@angular/router';
@Component({
selector: 'app-create-post',
templateUrl: './create-post.component.html',
styleUrls: ['./create-post.component.css']
})
export class CreatePostComponent implements OnInit {
constructor(private toastr: ToastrService, private http: HttpClient, private router: Router) { }
ngOnInit(): void {
}
submit(e:NgForm) {
if (e.form.status === "VALID") {
if (e.value.password !== e.value.rePassword) {
this.toastr.error("Mot de passe différent");
} else {
const data = {
firstName: e.value.firstName,
lastName: e.value.lastName,
userName: e.value.pseudo,
password: e.value.password,
role: 'USER'
};
//submit data
this.http.post("http://127.0.0.1:8000/api/v1/users", data).subscribe(response => {
this.toastr.success("Compte crée avec succès");
setTimeout(()=>{}, 2000);
this.router.navigate(['/login'])
},
error => {
this.toastr.error("Ce nom d'utilisateur n'est pas disponible.");
})
}
} else {
this.toastr.error("Veuillez remplir correctement tous les champs", "Valeurs manquantes ou invalides", {timeOut: 5000});
}
console.log(e.form.status)
}
}
...@@ -14,6 +14,7 @@ ...@@ -14,6 +14,7 @@
<li><a routerLink="/test" routerLinkActive="active">Test socket</a></li> <li><a routerLink="/test" routerLinkActive="active">Test socket</a></li>
<li *ngIf="!isAuth"><a routerLink="/login" routerLinkActive="active">Se connecter</a></li> <li *ngIf="!isAuth"><a routerLink="/login" routerLinkActive="active">Se connecter</a></li>
<li *ngIf="!isAuth"><a routerLink="/signup" routerLinkActive="active">Créer un compte</a></li> <li *ngIf="!isAuth"><a routerLink="/signup" routerLinkActive="active">Créer un compte</a></li>
<li *ngIf="isAuth"><a routerLink="/post/create" routerLinkActive="active">Poser une question</a></li>
<li (click)="logout()" *ngIf="isAuth"><a routerLinkActive="active">Se déconnecter</a></li> <li (click)="logout()" *ngIf="isAuth"><a routerLinkActive="active">Se déconnecter</a></li>
</ul> </ul>
</div> </div>
......
...@@ -11,7 +11,7 @@ import {Global} from "../global-classes/global"; ...@@ -11,7 +11,7 @@ import {Global} from "../global-classes/global";
}) })
export class HomeComponent implements OnInit { export class HomeComponent implements OnInit {
baseUrl: string = "http://127.0.0.1:8000/api/users"; baseUrl: string = "http://127.0.0.1:8000/api/v1/users";
constructor(private fb: FormBuilder, constructor(private fb: FormBuilder,
private http: HttpClient, private http: HttpClient,
...@@ -35,7 +35,7 @@ export class HomeComponent implements OnInit { ...@@ -35,7 +35,7 @@ export class HomeComponent implements OnInit {
}) })
}; };
this.http.get(this.baseUrl + "/all").subscribe(// httpOptions this.http.get(this.baseUrl).subscribe(// httpOptions
(data: any) => { (data: any) => {
console.log("list of users:: " + data[0].firstName + " " + data[0].lastName); console.log("list of users:: " + data[0].firstName + " " + data[0].lastName);
}, },
......
...@@ -49,6 +49,11 @@ export class LoginComponent implements OnInit { ...@@ -49,6 +49,11 @@ export class LoginComponent implements OnInit {
this.router.navigate(["/"]); this.router.navigate(["/"]);
this.jwtClientService.connect(data.toString()) this.jwtClientService.connect(data.toString())
this.toastr.success("Bon retour parmis nous " + authRequest.userName + " !") this.toastr.success("Bon retour parmis nous " + authRequest.userName + " !")
this.http.get<Array<Object>>(this.baseUrl + '?username=' + authRequest.userName).subscribe(data => {
if (data.length > 0) {
JwtClientService.userInfo = data[0];
}
})
}, },
error => { error => {
console.log("There is an error occurred: " + error) console.log("There is an error occurred: " + error)
......
...@@ -12,6 +12,7 @@ export class JwtClientService { ...@@ -12,6 +12,7 @@ export class JwtClientService {
public static isAuth: boolean = false; public static isAuth: boolean = false;
public static currentToken : string = ""; public static currentToken : string = "";
baseUrl: string = "http://127.0.0.1:8000/api/v1/users"; baseUrl: string = "http://127.0.0.1:8000/api/v1/users";
public static userInfo = {}
constructor(private http: HttpClient, constructor(private http: HttpClient,
private cookie: CookieService) { private cookie: CookieService) {
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment