Skip to content
Snippets Groups Projects
Commit 769d6195 authored by ywb16155's avatar ywb16155
Browse files

commit #3 - adding authentication services, linking authentication with database

parent 04298d22
No related branches found
No related tags found
No related merge requests found
Showing
with 281 additions and 18 deletions
......@@ -5,12 +5,14 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
@SpringBootApplication
@EnableJpaRepositories("com.diss.omppapp.repositories")
public class OmppappApplication {
public static void main(String[] args) {
......
package com.diss.omppapp.api;
import com.diss.omppapp.pojo.LoginPojo;
import com.diss.omppapp.services.AuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.HashMap;
import java.util.Map;
@RestController
class AuthController {
//This is dummy code currently used to solve API <-> WEB communication
@RequestMapping(value = "/auth", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String,String> getAuth() {
Map<String,String> authMap = new HashMap<>();
authMap.put("auth","false");
return authMap;
}
@Autowired
private AuthService authService;
@PostMapping(value = "/login",consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String,Boolean> getAuth(@RequestBody LoginPojo login) {
return authService.authorise(login.username, login.password);
}
}
......@@ -15,7 +15,8 @@ public class WebConfig implements WebMvcConfigurer {
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedMethods("PUT","DELETE","GET","POST","HEAD")
.allowedMethods("PUT","DELETE","GET","POST","HEAD", "OPTIONS")
.allowedHeaders("Content-Type","X-Requested-With","accept","authorization","Origin","Access-Control-Request-Headers")
.maxAge(3600);
}
};
......
......@@ -13,7 +13,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors();
http.cors().and().csrf().disable(); //TODO fix CSRF things...
}
@Bean
......
package com.diss.omppapp.database;
import com.diss.omppapp.entities.UserEntity;
import com.diss.omppapp.repositories.UserEntityRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Optional;
@Component
public class HibernateDBImpl implements ICommonDB {
@Autowired
private UserEntityRepository userEntityRepository;
@Override
public UserEntity findByUsername(String s) {
Optional<UserEntity> entity;
try {
entity = userEntityRepository.findByUsername(s);
} catch (NullPointerException npe) {
return getEmptyUserEntity();
}
if(entity.isPresent()) {
return entity.get();
}
return getEmptyUserEntity();
}
private UserEntity getEmptyUserEntity() {
return new UserEntity("","","",false);
}
}
package com.diss.omppapp.database;
import com.diss.omppapp.entities.UserEntity;
public interface ICommonDB {
UserEntity findByUsername(String s);
}
package com.diss.omppapp.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
@Entity
@Table(name = "omp_user")
public class UserEntity implements Serializable {
@Id
public String username;
@Column
public String password;
@Column
public String email;
@Column
public boolean isLecturer;
public UserEntity() {
}
public UserEntity(String username, String password, String email, boolean isLecturer){
this.username = username;
this.password = password;
this.email = email;
this.isLecturer = isLecturer;
}
public boolean isEmpty() {
return this.username.isEmpty() && this.password.isEmpty() && this.email.isEmpty();
}
}
package com.diss.omppapp.pojo;
public class LoginPojo {
public String username;
public String password;
public LoginPojo(String username, String password) {
this.username = username;
this.password = password;
}
}
package com.diss.omppapp.repositories;
import com.diss.omppapp.entities.UserEntity;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import java.util.Optional;
@Repository
public interface UserEntityRepository extends CrudRepository<UserEntity, String> {
Optional<UserEntity> findByUsername(String s);
}
package com.diss.omppapp.services;
import com.diss.omppapp.database.HibernateDBImpl;
import com.diss.omppapp.database.ICommonDB;
import com.diss.omppapp.entities.UserEntity;
import javassist.NotFoundException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import java.util.HashMap;
import java.util.Map;
@Component
public class AuthService {
@Autowired
private ICommonDB iCommonDB;
public AuthService() {
}
public Map<String,Boolean> authorise(String username, String password) {
Map<String,Boolean> map = new HashMap<>();
UserEntity entity = iCommonDB.findByUsername(username);
if(entity.isEmpty() || !compare(password,entity.password)) {
map.put("auth",false);
map.put("lec",false);
return map;
}
map.put("auth", true);
map.put("lec", entity.isLecturer);
return map;
}
private Boolean compare(String userHash, String dbHash) {
BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder.matches(userHash,dbHash);
}
}
spring.jpa.hibernate.ddl-auto=create
spring.datasource.url=jdbc:mysql://localhost:3306/dissdb
spring.jpa.hibernate.ddl-auto=none
spring.datasource.url=jdbc:mysql://localhost:3306/ompdb
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=apiuser
spring.datasource.password=password
......
import {Injectable} from '@angular/core';
import {HttpErrorResponse} from '@angular/common/http';
import {Observable, throwError} from 'rxjs';
@Injectable()
export class HttpErrorService {
public handleError(error: HttpErrorResponse): Observable<string> {
if (error.error instanceof ErrorEvent) {
console.error('Frontend or network error occurred.');
} else {
console.error('Backend error occurred');
}
return throwError('Something bad has happened. Please try again later.');
}
}
<div>
<h1>
Sorry the page you are looking for isn't here...
</h1>
</div>
import {Component} from '@angular/core';
@Component({
selector: 'app-404',
templateUrl: './page-not-found.component.html',
styleUrls: ['./page-not-found.component.css']
})
export class PageNotFoundComponent {
}
<div>
<div>
<h1>OMP+</h1>
</div>
<form [formGroup]="loginForm" (ngSubmit)="login()">
<div class="form-group">
<label for="username">Username</label>
<input id="username" type="text" formControlName="username" placeholder="username"
value="" [ngClass]="{'is-invalid' : loginForm.controls.username.errors && isSubmitted}">
<div *ngIf="loginForm.controls.username.errors && isSubmitted" class="invalid-feedback">
<div *ngIf="loginForm.controls.username.errors.required">Username is required.</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input id="password" type="password" formControlName="password" class="form-control" placeholder="password"
value="" [ngClass]="{'is-invalid' : loginForm.controls.password.errors && isSubmitted}">
<div *ngIf="loginForm.controls.password.errors && isSubmitted" class="invalid-feedback">
<div *ngIf="loginForm.controls.password.errors.required">Password is required.</div>
</div>
</div>
<div class="form-group">
<div>
<button type="submit" [disabled]="!loginForm.valid">Login</button>
</div>
</div>
</form>
</div>
import {Component, OnInit} from '@angular/core';
import {LoginService} from './login.service';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
loginForm: FormGroup;
isSubmitted: Boolean = false;
constructor(private loginService: LoginService,
private formBuilder: FormBuilder) {}
ngOnInit() {
this.loginForm = this.formBuilder.group({
username: ['', Validators.required],
password: ['', Validators.required]
});
}
private login(): void {
this.isSubmitted = true;
if (this.loginForm.invalid) {
return;
}
this.loginService.getLogin(this.loginForm.controls.username.value, this.loginForm.controls.password.value)
.subscribe((data) => console.log(data));
}
}
import {Injectable} from '@angular/core';
import {HttpClient, HttpHeaders} from '@angular/common/http';
import {HttpErrorService} from '../ErrorComponents/http-error.service';
import {catchError} from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
@Injectable()
export class LoginService {
constructor(private http: HttpClient, private errorService: HttpErrorService) {
}
public getLogin(username: String, password: String) {
return this.http.post('http://localhost:8080/login', {username: username, password: password}, httpOptions)
.pipe(
catchError(this.errorService.handleError),
);
}
}
<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
<h1>
Home
</h1>
Message: {{authObj.auth}}
<router-outlet></router-outlet>
</div>
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment