Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added user authentication #22

Closed
wants to merge 9 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
DATABASE_URL="postgresql://johndoe:randompassword@localhost:5432/mydb?schema=public"
SALT="this is a very insecure salt, change it"

MAIL_ENABLED=false
MAIL_SERVER="smtp.gmail.com"
MAIL_PORT=465
MAIL_USE_SSL=true
MAIL_USERNAME=""
MAIL_PASSWORD=""
MAIL_FROM='"YABin" <yabin@sohamsen.me>'

PUBLIC_REGISRATION_ENABLED=true
PUBLIC_URL="http://localhost:5173"
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ node_modules
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
.vercel
89 changes: 89 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
# Contributing

When contributing to this repository, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change.

Please note we have a code of conduct, please follow it in all your interactions with the project.

## Pull Request Process

1. Ensure any install or build dependencies are removed before the end of the layer when doing a
build.
2. Update the README.md with details of changes to the interface, this includes new environment
variables, exposed ports, useful file locations and container parameters.
3. Ensure that the code is adhering to the existing code style.

## Code of Conduct

### Our Pledge

In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to making participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.

### Our Standards

Examples of behavior that contributes to creating a positive environment
include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting

### Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective action in
response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.

### Scope

This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.

### Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at contact@sohamsen.me. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.

### Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ Well, cause no pastebin I could find had ALL of the following features:
- View raw pastes. Normally, encrypted pastebins do not have this. With this site, you can either get the Base64-encoded encrypted paste, or decrypt it on the server side (even with the password) and get the raw paste.
- Keyboard shortcuts!
- And of course, being fully open-source and easily self-hostable.
- **NEW** Ability to edit pastes after creation, and a dashboard for viewing all your pastes.
- **Comes with a CLI tool to create and read pastes from the command line!**
- **It can even be run on edge servers and in serverless environments!**

Expand All @@ -48,7 +49,17 @@ See [cli/README.md](cli/README.md) for detailed instructions and library usage.

**Requirements:** Node.js (tested on 18+, should work with 14+), and a SQL database (tested on PostgreSQL, should work with MySQL and SQLite).

Right now, it is using PostgreSQL (cause I had a server lying around). However, it can be run using any SQL DB such as SQLite or MySQL. To use other backends, please update the provider in [schema.prisma](src/lib/server/prisma/schema.prisma)
Right now, my instance is using PostgreSQL on Vercel. However, it can be run using any SQL DB such as SQLite or MySQL. To use other backends, please update the provider in [schema.prisma](src/lib/server/prisma/schema.prisma)

### .env Configuration

`DATABASE_URL` needs to point to a running SQL database. It uses PostgreSQL by default, but can be changed to MySQL or SQLite by modifying the provider in [schema.prisma](src/lib/server/prisma/schema.prisma).

Remember to modify `SALT` to something secure if you plan on using user accounts.

You can disable or enable public registration by modifying the `PUBLIC_REGISRATION_ENABLED` variable to `true` or `false`.

By default, if no e-mail services are configured, all user accounts will be marked as validated. To enable e-mail validation, please configure the `MAIL_*` variables.

#### Locally

Expand Down
14 changes: 7 additions & 7 deletions cli/poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,16 @@
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
"lint": "prettier --plugin-search-dir . --check . && eslint .",
"format": "prettier --plugin-search-dir . --write ."
"format": "prettier --plugin-search-dir . --write .",
"postinstall": "prisma generate --schema=./src/lib/server/prisma/schema.prisma"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^2.0.0",
"@sveltejs/adapter-node": "^1.2.4",
"@sveltejs/adapter-vercel": "^3.0.3",
"@sveltejs/kit": "^1.5.0",
"@types/node-cron": "^3.0.7",
"@types/nodemailer": "^6.4.11",
"@types/prismjs": "^1.26.0",
"@types/sanitize-html": "^2.9.0",
"@typescript-eslint/eslint-plugin": "^5.45.0",
Expand All @@ -24,7 +27,7 @@
"eslint": "^8.28.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-svelte": "^2.26.0",
"postcss": "^8.4.24",
"postcss": "^8.4.31",
"prettier": "^2.8.0",
"prettier-plugin-svelte": "^2.8.1",
"prisma": "^4.15.0",
Expand All @@ -40,7 +43,9 @@
"dependencies": {
"@prisma/client": "^4.15.0",
"base64-js": "^1.5.1",
"nanoid": "^5.0.1",
"node-cron": "^3.0.2",
"nodemailer": "^6.9.5",
"prism-themes": "^1.9.0",
"prismjs": "^1.29.0",
"sanitize-html": "^2.10.0"
Expand Down
18 changes: 15 additions & 3 deletions src/lib/crypto.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
import base64 from 'base64-js';

export async function encrypt(plaintext: string) {
export async function encrypt(plaintext: string, keyStr: string | undefined = undefined) {
const encoder = new TextEncoder();

const iv: Uint8Array = crypto.getRandomValues(new Uint8Array(12));
const ivStr = base64.fromByteArray(iv);

const alg = { name: 'AES-GCM', iv, length: 256 };

const key = (await crypto.subtle.generateKey(alg, true, ['encrypt'])) as CryptoKey;
const keyStr = base64.fromByteArray(new Uint8Array(await crypto.subtle.exportKey('raw', key)));
let key: CryptoKey;
if (!keyStr) {
key = (await crypto.subtle.generateKey(alg, true, ['encrypt'])) as CryptoKey;
keyStr = base64.fromByteArray(new Uint8Array(await crypto.subtle.exportKey('raw', key)));
} else {
key = await crypto.subtle.importKey('raw', base64.toByteArray(keyStr), alg, false, ['encrypt']);
}
const enc = await crypto.subtle.encrypt(alg, key, encoder.encode(plaintext));
const encStr = base64.fromByteArray(new Uint8Array(enc));

Expand Down Expand Up @@ -92,3 +97,10 @@ export async function decryptWithPassword(ciphertext: string, iv: string, passwo
const dec = await crypto.subtle.decrypt(alg, key, base64.toByteArray(ciphertext));
return decoder.decode(dec);
}

export async function hashPassword(password: string, salt: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(password + salt);
const hash = await crypto.subtle.digest('SHA-512', data);
return base64.fromByteArray(new Uint8Array(hash));
}
40 changes: 40 additions & 0 deletions src/lib/server/auth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { SALT } from '$env/static/private';
import { hashPassword } from '$lib/crypto';
import prisma from '@db';
import type { Cookies } from '@sveltejs/kit';

export const getUserIdFromCookie = async (cookies: Cookies) => {
const token = cookies.get('token');
if (!token) return null;

const authToken = await prisma.authToken.findFirst({
where: { token, expiresAt: { gt: new Date() } },
include: { user: { select: { id: true, verified: true } } }
});
if (!authToken) return null;
if (!authToken.user.verified) return null;

return authToken.user.id;
};

export const generateVerificationHash = async (userId: string) => {
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user) throw new Error('User not found');

const hash = await hashPassword(`${user.email}${user.id}${user.password}${user.verified}`, SALT);
return hash;
};

export const validateVerificationHash = async (userId: string, hash: string) => {
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user) return false;

const newHash = await hashPassword(
`${user.email}${user.id}${user.password}${user.verified}`,
SALT
);
if (newHash !== hash) return false;

await prisma.user.update({ where: { id: userId }, data: { verified: true } });
return true;
};
39 changes: 39 additions & 0 deletions src/lib/server/email/base.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import nodemailer from 'nodemailer';
import {
MAIL_ENABLED,
MAIL_SERVER,
MAIL_PASSWORD,
MAIL_PORT,
MAIL_USERNAME,
MAIL_USE_SSL,
MAIL_FROM
} from '$env/static/private';

export async function sendEmail(to: string, subject: string, content: string) {
if (MAIL_ENABLED !== 'true') {
return false;
}

const transporter = nodemailer.createTransport({
host: MAIL_SERVER,
port: Number(MAIL_PORT),
secure: MAIL_USE_SSL === 'true',
auth: {
user: MAIL_USERNAME,
pass: MAIL_PASSWORD
}
});

const info = await transporter.sendMail({
from: MAIL_FROM,
to,
subject,
text: content
});

if (info.accepted.length === 0) {
return false;
}

return true;
}
23 changes: 23 additions & 0 deletions src/lib/server/email/verify.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { PUBLIC_URL } from '$env/static/public';
import prisma from '@db';
import { generateVerificationHash } from '../auth';
import { sendEmail } from './base';

export const sendVerificationEmail = async (userId: string) => {
const user = await prisma.user.findUnique({ where: { id: userId } });
if (!user) return false;

const hash = await generateVerificationHash(userId);

const verifyUrl = `${PUBLIC_URL}/validate?hash=${encodeURIComponent(
hash
)}&userId=${encodeURIComponent(userId)}`;

const content = `To verify your email, please click the following link: ${verifyUrl}`;
const subject = 'YABin: Verify your email';

const sent = await sendEmail(user.email, subject, content);
if (!sent) return false;

return true;
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
-- AlterTable
ALTER TABLE "Paste" ADD COLUMN "ownerId" BIGINT;

-- CreateTable
CREATE TABLE "User" (
"id" BIGSERIAL NOT NULL,
"username" TEXT NOT NULL,
"email" TEXT NOT NULL,
"password" TEXT NOT NULL,
"name" TEXT NOT NULL,

CONSTRAINT "User_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "User_username_key" ON "User"("username");

-- CreateIndex
CREATE UNIQUE INDEX "User_email_key" ON "User"("email");

-- AddForeignKey
ALTER TABLE "Paste" ADD CONSTRAINT "Paste_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
-- CreateTable
CREATE TABLE "AuthToken" (
"id" BIGSERIAL NOT NULL,
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMP(3) NOT NULL,
"token" TEXT NOT NULL,
"userId" BIGINT NOT NULL,

CONSTRAINT "AuthToken_pkey" PRIMARY KEY ("id")
);

-- CreateIndex
CREATE UNIQUE INDEX "AuthToken_token_key" ON "AuthToken"("token");

-- AddForeignKey
ALTER TABLE "AuthToken" ADD CONSTRAINT "AuthToken_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE RESTRICT ON UPDATE CASCADE;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
-- DropForeignKey
ALTER TABLE "AuthToken" DROP CONSTRAINT "AuthToken_userId_fkey";

-- AddForeignKey
ALTER TABLE "AuthToken" ADD CONSTRAINT "AuthToken_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
Loading