Skip to content

Commit

Permalink
Merge pull request #4 from APSN4/feature/password
Browse files Browse the repository at this point in the history
feature: encrypt code snippets with a password
  • Loading branch information
nuromirzak authored Aug 17, 2024
2 parents 23f7db8 + aa8b981 commit 780e005
Show file tree
Hide file tree
Showing 12 changed files with 201 additions and 10 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,7 @@ out/
.vscode/

### H2 Database ###
*.db
*.db

### macOS files ###
.DS_Store
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,16 @@ public GetController(@Autowired CodeService codeService) {
}

@GetMapping("/code/{N}")
public String getNthCode(@PathVariable String N, Model model) {
public String getNthCode(@PathVariable String N, @RequestParam(value = "password", required = false) String password, Model model) {
try {
Code currentCode = codeService.getById(N);

if (password == null) password = "";
if (!password.equals(currentCode.getPassword())) {
return "password";
}
codeService.refreshCode(currentCode);

DateDTO dateDTO = codeService.formatDate(currentCode.getDate());
model.addAttribute("pieceOfCode", currentCode);
model.addAttribute("dateDTO", dateDTO);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
package codes.sharing.sharingcodes.controller;

import codes.sharing.sharingcodes.dto.PasswordDTO;
import codes.sharing.sharingcodes.model.Code;
import codes.sharing.sharingcodes.service.CodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.util.HashMap;
import java.util.Map;

@Controller
Expand Down Expand Up @@ -40,4 +43,15 @@ public Map<String, String> createApiCode(@RequestBody Code newCode) {
public Object getLatestApiCodes() {
return codeService.getLatestNCode(10);
}

@PostMapping(value = "/api/code/password", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public ResponseEntity<Object> checkPassword(@RequestBody PasswordDTO passwordDTO) {
Code currentCode = codeService.getById(passwordDTO.getId());
if (currentCode.getPassword().equals(passwordDTO.getPassword())) {
return ResponseEntity.ok().build();
} else {
return ResponseEntity.badRequest().build();
}
}
}
35 changes: 35 additions & 0 deletions src/main/java/codes/sharing/sharingcodes/dto/PasswordDTO.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package codes.sharing.sharingcodes.dto;

public class PasswordDTO {

public PasswordDTO(String password, String id) {
this.password = password;
this.id = id;
}

public PasswordDTO(String password) {
this.password = password;
}
public PasswordDTO() {
this.password = "";
}

private String password;
private String id;

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}
}
12 changes: 12 additions & 0 deletions src/main/java/codes/sharing/sharingcodes/model/Code.java
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ public class Code {
@Column(name = "timelimit")
private boolean timeLimit;

@Column(name = "password")
private String password;

public Code() {

}
Expand All @@ -53,6 +56,7 @@ public Code(Code code) {
if (this.time > 0) {
this.timeLimit = true;
}
this.password = code.getPassword() == null ? "" : code.getPassword();
}

public String getId() {
Expand Down Expand Up @@ -131,4 +135,12 @@ public String shortCode() {
return getCode();
}
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package codes.sharing.sharingcodes.service;

import codes.sharing.sharingcodes.dto.DateDTO;
import codes.sharing.sharingcodes.dto.PasswordDTO;
import codes.sharing.sharingcodes.model.Code;

import java.util.List;
Expand All @@ -11,6 +12,8 @@ public interface CodeService {

public void putCode(Code newCode);

public void refreshCode(Code code);

public List<Code> getLatestNCode(int n);

public boolean isExist(String id);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package codes.sharing.sharingcodes.service;

import codes.sharing.sharingcodes.dto.DateDTO;
import codes.sharing.sharingcodes.dto.PasswordDTO;
import codes.sharing.sharingcodes.exceptions.NotFoundSnippet;
import codes.sharing.sharingcodes.model.Code;
import codes.sharing.sharingcodes.repository.CodeRepository;
Expand All @@ -24,10 +25,6 @@ public CodeServiceImpl(@Autowired CodeRepository repo) {

@Override
public Code getById(String id) {
Code code = repo.findById(id).orElseThrow(() -> new NotFoundSnippet(id));
if (code.hasLimit()) {
refresh(code);
}
return repo.findById(id).orElseThrow(() -> new NotFoundSnippet(id));
}

Expand All @@ -38,6 +35,14 @@ public void putCode(Code newCode) {
repo.save(code);
}

@Override
public void refreshCode(Code code) {
if (code.hasLimit()) {
refresh(code);
}
}


@Override
public List<Code> getLatestNCode(int n) {
List<Code> codes = (List<Code>) repo.findAll();
Expand Down Expand Up @@ -78,7 +83,7 @@ public List<Code> superGetAll() {
private void refresh(Code code) {
if (code.isViewsLimit() && code.getViews() >= 0) {
code.setViews(code.getViews() - 1);
if (code.getViews() < 0) {
if (code.getViews() <= 0) {
repo.delete(code);
return;
}
Expand Down
33 changes: 31 additions & 2 deletions src/main/resources/static/js/myScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ function send() {
let object = {
"code": document.getElementById("code_snippet").value,
"views": document.getElementById("views_restriction").value,
"time": document.getElementById("time_restriction").value
"time": document.getElementById("time_restriction").value,
"password": document.getElementById("password_field").value
};

let json = JSON.stringify(object);
Expand Down Expand Up @@ -55,4 +56,32 @@ function send() {
errorCode.innerHTML = xhr.status + " " + xhr.statusText;
return;
}
}
}

function check() {
const codeId = location.pathname.substring(6);
var object = {
"password": document.getElementById("password_field").value,
"id": codeId
};
let json = JSON.stringify(object);

try {
xhr = new XMLHttpRequest();
xhr.open("POST", '/api/code/password', false)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(json);

var url = location.protocol + '//' + location.host + location.pathname + '?password=' + object.password;

if (xhr.status == 200) {
window.location.href = url;
} else if (xhr.status == 400){
dangerMessage.style.display = "block";
} else {
window.location.href = url;
}
} catch (error) {
console.error(error.message);
}
}
1 change: 1 addition & 0 deletions src/main/resources/templates/getcode.ftlh
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="page-status" content="available"/>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/styles.css">
<script src="https://kit.fontawesome.com/224143ea2d.js" crossorigin="anonymous"></script>
Expand Down
11 changes: 11 additions & 0 deletions src/main/resources/templates/index.ftlh
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,18 @@
<small class="form-text text-muted">This will allow viewing a code snippet for a certain period of time, and after its expiration, the code snippet is deleted from the database.</small>
</div>
</div>
<p></p>
<button id="send_snippet" type="submit" class="btn btn-primary">Submit</button>
<button id="set_password" type="button" class="btn btn-outline-primary" data-toggle="collapse" href="#collapsePassword" role="button" aria-expanded="false" aria-controls="collapsePassword">Set password</button>
<p></p>
<div class="collapse" id="collapsePassword">
<div class="input-group mb-3">
<div class="input-group-prepend">
<span class="input-group-text" id="inputGroup-sizing-default">Password</span>
</div>
<input type="text" class="form-control" id="password_field" aria-label="Password input" aria-describedby="inputGroup-sizing-default">
</div>
</div>
</div>
</form>
</div>
Expand Down
67 changes: 67 additions & 0 deletions src/main/resources/templates/password.ftlh
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="page-status" content="unavailable"/>
<link rel="stylesheet" href="/css/bootstrap.min.css">
<link rel="stylesheet" href="/css/styles.css">
<script src="https://kit.fontawesome.com/224143ea2d.js" crossorigin="anonymous"></script>
<script src="/js/myScript.js"></script>
<title>Secret code snippet!</title>
<link rel="icon" type="image/png" href="/imgs/code-pngrepo-com.png">
</head>

<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="/">Sharing <img src="/imgs/code-pngrepo-com.png" alt="" style="height: 1em;"> Codes</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNavAltMarkup">
<ul class="navbar-nav mr-auto">
<li><a class="nav-link" href="/code/latest">Recent codes</a></li>
<li><a class="nav-link" href="/code/usage">Usage</a></li>
<li><a class="nav-link" href="/code/about">About</a></li>
</ul>
<span class="navbar-text">
<a href="https://github.com/nuromirzak/sharing-codes" target="_blank">
<i class="fa-brands fa-github fa-2xl" style="color: black"></i>
</a>
</span>
</div>
</nav>

<div class="container p-3">
<form action="" onsubmit="check()">
<div class="form-group">
<label for="code_snippet"><h1>Secret code snippet 😎</h1></label>
<div class="d-flex justify-content-center">
<div class="row">
<div class="col">
<label for="password_field">Enter your password:</label>
<div class="d-flex justify-content-center">
<input type="text" class="form-control" id="password_field" placeholder="Secret password" style="margin-right: 10px;">
<button id="open_snippet" type="submit" class="btn btn-primary">Submit</button>
</div>
<small class="form-text text-muted">This code snippet has been encrypted. You must enter your password to view this code.</small>
<div class="alert alert-danger danger-message" role="alert" style="display: none;">
<h4 class="alert-heading">Oops!...</h4>
<p></p>
<p>Please check that you have entered the correct data.</p>
</div>
</div>
</div>
</div>
</div>
</form>
</div>


<script src="/js/jquery.slim.min.js"></script>
<script src="/js/bootstrap.bundle.min.js"></script>
</body>

</html>
6 changes: 5 additions & 1 deletion src/main/resources/templates/recent.ftlh
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,11 @@
<h5 class="mb-1">${pieceOfCode.getId()}</h5>
<small class="text-muted"><span id="load_date">${pieceOfCode.date}</span></small>
</div>
<p class="mb-1">${pieceOfCode.shortCode()}</p>
<#if !pieceOfCode.getPassword()?has_content>
<p class="mb-1">${pieceOfCode.shortCode()}</p>
<#else>
<p class="mb-1">This is an encrypted code snippet.</p>
</#if>
</a>
</#list>
</div>
Expand Down

0 comments on commit 780e005

Please sign in to comment.