Skip to content

Commit

Permalink
Merge pull request #2 from wshchocolatine/dev
Browse files Browse the repository at this point in the history
Clean code and change encryption algorithm cbc -> ctr
  • Loading branch information
wshchocolatine committed Feb 22, 2022
2 parents c0243f7 + 6874b5c commit dc2485b
Show file tree
Hide file tree
Showing 14 changed files with 109 additions and 262 deletions.
20 changes: 20 additions & 0 deletions app/Controllers/Http/AuthController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import StoreUserValidator from 'App/Validators/StoreUserValidator'
import FinishStoreUserValidator from 'App/Validators/FinishStoreUserValidator'
import Database from '@ioc:Adonis/Lucid/Database'
import { socketAuth } from '../../utils/socket-auth/index'
//import { rword } from 'rword'

let crypto = require('crypto')
let CryptoJS = require('crypto-js')
Expand Down Expand Up @@ -99,6 +100,25 @@ export default class AuthController {
}
}

/*public async Seed_Phrase({ response, session }: HttpContextContract): Promise<void> {
try {
if (session.has('username')) {
//Generate seed phrase
let seed_phrase = rword.generate(12)
//Putting it in session
session.put('seed_phrase', seed_phrase)
//Sending it
return response.created({ status: "created", data: { 'seed_phrase': seed_phrase }})
} else {
return response.forbidden({ status : "forbidden" })
}
} catch(e) {
return response.internalServerError({ status : "internalServerError", errors: e })
}
}*/

public async Login({ response, request, auth, session }: HttpContextContract): Promise<void> {
try {
//Checking data
Expand Down
33 changes: 2 additions & 31 deletions app/Controllers/Http/ConversationsController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export default class ConversationsController {
let key_AES = crypto.privateDecrypt(Buffer.from(session.get('key')), Buffer.from(key_encrypted, 'base64'))

//Decrypt message
let decipher = crypto.createDecipheriv('aes-192-cbc', key_AES, Buffer.from(iv, 'hex'))
let decipher = crypto.createDecipheriv('aes-192-ctr', key_AES, Buffer.from(iv, 'hex'))
let decrypted_msg = decipher.update(element.last_msg_content, 'hex', 'utf-8')
decrypted_msg += decipher.final('utf-8')
element.last_msg_content = decrypted_msg
Expand Down Expand Up @@ -86,7 +86,7 @@ export default class ConversationsController {
let key_AES = crypto.privateDecrypt(Buffer.from(session.get('key')), Buffer.from(key_encrypted, 'base64'))

//Decrypt message
let decipher = crypto.createDecipheriv('aes-192-cbc', key_AES, Buffer.from(iv, 'hex'))
let decipher = crypto.createDecipheriv('aes-192-ctr', key_AES, Buffer.from(iv, 'hex'))
let decrypted_msg = decipher.update(element.conversation.last_msg_content, 'hex', 'utf-8')
decrypted_msg += decipher.final('utf-8')
element.conversation.last_msg_content = decrypted_msg
Expand Down Expand Up @@ -116,33 +116,4 @@ export default class ConversationsController {
}
}

//Never used so not updated
/* public async Post({ response, request, auth }: HttpContextContract): Promise<any> {
try {
//Checking Data
try {
await request.validate(StoreConversationValidator)
} catch(e) {
return parseInt(e.messages.errors[0].message)
}
//Getting Data
let { receiver, last_msg_content } = await request.validate(StoreConversationValidator)
//Creating conv
let payload = {
id: parseInt(String(Math.floor(Math.random() * Date.now())).slice(0, 10)),
author: auth.user?.id,
receiver: receiver,
last_msg_content: last_msg_content,
last_msg_author: auth.user?.id,
last_msg_read: false,
}
await Conversation.create(payload)
//Everything 😀
return response.created()
} catch(e) {
return response.internalServerError()
}
} */
}
19 changes: 5 additions & 14 deletions app/Controllers/Http/MessagesController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,8 @@ export default class MessagesController {
return response.badRequest({ status: "badRequest", errors: e })
}

//Checking auth
if (auth.user!.public_key === undefined) {
return response.internalServerError({ errors: 'Problème de sessions, contacte moi sur Discord :)' })
}

//Getting data
let { receiver_username,receiver_tag, content } = await request.validate(StoreFirstMessageValidator)
let { receiver_username, receiver_tag, content } = await request.validate(StoreFirstMessageValidator)

//Getting the receiver_id
let receiver_id_array = await Database.from('users').where('username', receiver_username).andWhere('tag', receiver_tag).select('id')
Expand All @@ -43,7 +38,7 @@ export default class MessagesController {
let iv = crypto.randomBytes(16)

//Creating the cipher
let cipher = crypto.createCipheriv('aes-192-cbc', key, iv)
let cipher = crypto.createCipheriv('aes-192-ctr', key, iv)
let encrypted_msg = cipher.update(content, 'utf-8', 'hex')
encrypted_msg += cipher.final('hex')

Expand Down Expand Up @@ -137,11 +132,7 @@ export default class MessagesController {
//Getting data
let { conv_id, content } = await request.validate(StoreMessageValidator)
let user_id = auth.user!.id

//Getting receiver_id and user_connected_id
//let receiver_id = (await Participant.query().where('conversation_id', conv_id).andWhereNot('user_id', user_id).select('user_id'))[0].user_id
//let authorAndReceiver = await Conversation.query().where('id', conv_id).select('author', 'receiver')
//let receiver_id = authorAndReceiver[0].author = auth.user!.id ? authorAndReceiver[0].receiver : authorAndReceiver[0].author


//INSERTING INTO DATABASE

Expand All @@ -151,7 +142,7 @@ export default class MessagesController {
let key_AES = crypto.privateDecrypt(Buffer.from(session.get('key')), Buffer.from(key_encrypted, 'base64'))

//Encrypting message
let cipher = crypto.createCipheriv('aes-192-cbc', key_AES, Buffer.from(iv, 'hex'))
let cipher = crypto.createCipheriv('aes-192-ctr', key_AES, Buffer.from(iv, 'hex'))
let encrypted_msg = cipher.update(content, 'utf-8', 'hex')
encrypted_msg += cipher.final('hex')

Expand Down Expand Up @@ -209,7 +200,7 @@ export default class MessagesController {

//2.Decrypting messages
messages.forEach((element) => {
let decipher = crypto.createDecipheriv('aes-192-cbc', key_AES, Buffer.from(iv, 'hex'))
let decipher = crypto.createDecipheriv('aes-192-ctr', key_AES, Buffer.from(iv, 'hex'))
let decrypted_msg = decipher.update(element.content, 'hex', 'utf-8')
decrypted_msg += decipher.final('utf-8')
element.content = decrypted_msg
Expand Down
12 changes: 0 additions & 12 deletions app/Controllers/Http/TriesController.ts

This file was deleted.

159 changes: 63 additions & 96 deletions app/Controllers/Http/UsersController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@ import User from 'App/Models/User'
import Application from '@ioc:Adonis/Core/Application'
import ChangeDescriptionValidator from 'App/Validators/ChangeDescriptionValidator'
import ChangeUsernameValidator from 'App/Validators/ChangeUsernameValidator'
/* import ChangePasswordValidator from 'App/Validators/ChangePasswordValidator'
import Hash from '@ioc:Adonis/Core/Hash'
import Key from 'App/Models/Key'
let crypto = require('crypto') */

export default class UsersController {
public async Account({ response, auth }: HttpContextContract): Promise<void> {
Expand Down Expand Up @@ -116,106 +121,68 @@ export default class UsersController {
)
}

/* public async Check_STCP({ request, response, auth }: HttpContextContract): Promise<void> {
try {
//Checking data
try {
await request.validate(CheckSTCPValidator)
} catch (e) {
return response.badRequest({ errors: e })
}
//Getting data
let { stcp } = await request.validate(CheckSTCPValidator)
//Checking it
//Query db
let userData = (await Database.from('users').where('id', auth.user!.id))[0]
if (await Hash.verify(userData.stcp, stcp)) {
//If answer is good
await Database.from('users').update({ is_changing_password: true })
return response.created({ status: "created" })
/* public async Change_Password({ request, response, auth, session }: HttpContextContract): Promise<void> {
try {
//Authenticating the request
await auth.check()
//Getting data
let { seed_phrase, new_password, email } = await request.validate(ChangePasswordValidator)
//If user is already logged in
if (auth.isLoggedIn) {
//Getting user's id and getting user informations
let user_id = auth.user!.id
let user = await User.findOrFail(user_id)
//Getting hashed seed phrase
let seed_phrase_hashed = user.seed_phrase
//Checking if seed phrase correct
if (await Hash.verify(seed_phrase_hashed, seed_phrase)) {
//Changing user's password
user.password = new_password
user.private_key = session.get('key')
await user.save()
} else {
//If answer is false
return response.unauthorized({ status: "unauthorized" })
}
} catch (e) {
return response.internalServerError({ status: "internalServerError", errors: e })
}
}
public async Check_Pass({ request, response, auth }: HttpContextContract): Promise<void> {
try {
//Checking data
try {
await request.validate(CheckPassValidator)
} catch (e) {
return response.badRequest({ status: "badRequest", errors: e })
}
//Getting data
let { password } = await request.validate(CheckPassValidator)
//Checking it
//Query db
let userData = (await Database.from('users').where('id', auth.user!.id))[0]
if (await Hash.verify(userData.password, password)) {
//If answer is good
await Database.from('users').update({ is_changing_password: true })
return response.created({ status: "created" })
} else {
//Getting user informations
let user = await User.findByOrFail('email', email)
//Getting hashed seed phrase
let seed_phrase_hashed = user.seed_phrase
//Checking if seed phrase is correct
if (await Hash.verify(seed_phrase_hashed, seed_phrase_hashed)) {
//Recreating keys
let { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: { type: 'spki', format: 'pem' },
privateKeyEncoding: { type: 'pkcs8', format: 'pem' }
})
let user_id = user.id
let keys = await Key.query().where('owner_id', user_id)
keys.forEach(key => {
key.
})
//Updating user profile
user.public_key = publicKey
user.private_key = privateKey
user.password = new_password
await user.save()
} else {
//If answer is false
return response.unauthorized({ status: "unauthorized" })
}
} catch (e) {
return response.internalServerError({ status: "internalServerError", errors: e })
}
}
public async Change_Pass({ request, response, session, auth }: HttpContextContract): Promise<any> {
try {
//Checking process
if ((await User.findOrFail(auth.user!.id)).is_changing_password === false) {
return response.forbidden({ status: "forbidden" })
return response.unauthorized({ status : "unauthorized" })
}
//Checking data
try {
await request.validate(ChangePasswordValidator)
} catch (e) {
return response.badRequest({ status: "badRequest", errors: e })
}
//Getting data
let { password } = await request.validate(ChangePasswordValidator)
//QUERYING DB
//Changing password
let user = await User.findOrFail(auth.user!.id) //Getting user
user.password = password //Saving new password
//Getting private_key to cipher it later with the new password
let private_key = session.get('key')
user.private_key = private_key
//Closing the process by changing this field from true to false
user.is_changing_password = false
//Saving changements to the user
await user.save()
//Everything good!!!
return response.created({ status: "created" })
} catch (e) {
return response.internalServerError({ status: "internalServerError", errors: e })
}
} */
} */

/* import Database from '@ioc:Adonis/Lucid/Database'
import Hash from '@ioc:Adonis/Core/Hash'
import CheckPassValidator from 'App/Validators/CheckPassValidator'
import CheckSTCPValidator from 'App/Validators/CheckSTCPValidator'
import ChangePasswordValidator from 'App/Validators/ChangePasswordValidator' */
}
2 changes: 1 addition & 1 deletion app/Models/User.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ export default class User extends BaseModel {
}

if(user.description === "") {
user.description = 'Ake > Whatsapp'
user.description = 'Hey !'
}
}

Expand Down
16 changes: 10 additions & 6 deletions app/Validators/ChangePasswordValidator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,14 @@ export default class ChangePasswordValidator {
* ```
*/
public schema = schema.create({
password: schema.string({ trim: true }, [
rules.required(),
rules.regex(new RegExp('(?=^.{8,}$)(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*]+).*$'))
])
seed_phrase: schema.string({ trim: false }, [
rules.required()
]),
email: schema.string.optional(),
new_password: schema.string({ trim: true }, [
rules.required(),
rules.regex(new RegExp('(?=^.{8,}$)(?=.*[0-9])(?=.*[A-Z])(?=.*[a-z])(?=.*[!@#$%^&*]+).*$'))
])
})

/**
Expand All @@ -43,7 +47,7 @@ export default class ChangePasswordValidator {
*
*/
public messages = {
'required': 'The {{ field }} field is required',
'string': 'The {{ field }} field should be a string'
'required': 'The {{ field }} field is required',
'string': 'The {{ field }} field should be a string'
}
}

0 comments on commit dc2485b

Please sign in to comment.