Skip to content

Instantly share code, notes, and snippets.

View olehcambel's full-sized avatar
🐍

Олег Моисеенко olehcambel

🐍
  • @[object Object]
  • Kyiv
View GitHub Profile
@olehcambel
olehcambel / interface-union.go
Created April 22, 2020 18:48
using union to merge 2 interfaces
type Reader interface {
Read(p []byte) (n int, err error)
Close() error
}
type Writer interface {
Write(p []byte) (n int, err error)
Close() error
}
package main
import (
"log"
"time"
)
func main() {
c1 := make(chan string)
c2 := make(chan string)
@olehcambel
olehcambel / pointer.go
Last active April 18, 2020 08:00
example of pointer's usage. In general, all methods on a given type should have either value or pointer receivers, but not a mixture of both.
package main
import (
"fmt"
)
type counter struct {
I int
}
@olehcambel
olehcambel / copy.go
Created March 25, 2020 20:24
go copy impl
func copy(dst, src []T) int {
for i := range dst {
src[i] = dst[i]
}
return cap(dst) - cap(src)
}
t := make([]byte, len(s), (cap(s)+1)*2)
copy(t, s)
@olehcambel
olehcambel / hello-node.js
Created March 22, 2020 19:18 — forked from nf/hello-node.js
Hello world web server that scales across multiple processors
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
@olehcambel
olehcambel / tokens.md
Created September 23, 2019 07:07 — forked from zmts/tokens.md
Про токены, JSON Web Tokens (JWT), аутентификацию и авторизацию. Token-Based Authentication

Про токены, JSON Web Tokens (JWT), аутентификацию и авторизацию. Token-Based Authentication

Основы:

Аутентификация(authentication, от греч. αὐθεντικός [authentikos] – реальный, подлинный; от αὐθέντης [authentes] – автор) - это процесс проверки учётных данных пользователя (логин/пароль). Проверка подлинности пользователя путём сравнения введённого им логина/пароля с данными сохранёнными в базе данных.

Авторизация(authorization — разрешение, уполномочивание) - это проверка прав пользователя на доступ к определенным ресурсам.

Например после аутентификации юзер sasha получает право обращатся и получать от ресурса "super.com/vip" некие данные. Во время обращения юзера sasha к ресурсу vip система авторизации проверит имеет ли право юзер обращатся к этому ресурсу (проще говоря переходить по неким разрешенным ссылкам)

@olehcambel
olehcambel / app.ts
Created March 30, 2019 13:04
async error handling with express
import { asyncWrap } from './async-wrap';
const app = express();
asyncWrap();
@olehcambel
olehcambel / onsuccess.helper.ts
Created March 13, 2019 11:59
generic + overload
interface OnSuccessResponse<T> {
statusCode: number
message: string
data: T
error: null
}
export function onSuccess<T>(): OnSuccessResponse<T>
export function onSuccess<T>(params: { message?: string, data?: T | null }): OnSuccessResponse<T>
export function onSuccess<T>(params: {message?: string, data?: T | null}={}) {
@olehcambel
olehcambel / app.js
Created February 28, 2019 21:07 — forked from joshnuss/app.js
Express.js role-based permissions middleware
// the main app file
import express from "express";
import loadDb from "./loadDb"; // dummy middleware to load db (sets request.db)
import authenticate from "./authentication"; // middleware for doing authentication
import permit from "./permission"; // middleware for checking if user's role is permitted to make request
const app = express(),
api = express.Router();
// first middleware will setup db connection
@olehcambel
olehcambel / db.js
Last active January 12, 2019 20:22
const mysql = require('mysql')
const pool = mysql.createConnection({
host: config.db.host,
user: config.db.user,
password: config.db.password,
database: config.db.database,
});
class DB {