diff --git a/.dockerignore b/.dockerignore index 9c1a3cc..22d669a 100644 --- a/.dockerignore +++ b/.dockerignore @@ -11,12 +11,13 @@ docs config/config.json package-withSequelize.json +temp/ #Sequelise Temporary Ignore list -models/ -config/ -migrations/ -src/helpers/api/installSequelize.ts -src/helpers/installation.ts -src/helpers/models.ts -.sequelizerc +# models/ +# config/ +# migrations/ +# src/helpers/api/installSequelize.ts +# src/helpers/installation.ts +# src/helpers/models.ts +# .sequelizerc diff --git a/.gitignore b/.gitignore index c0706d6..478bb1a 100644 --- a/.gitignore +++ b/.gitignore @@ -46,12 +46,12 @@ COMBINEDCOMMITMESSAGE config/config.json package-withSequelize.json - +temp/ #Sequelise Temporary Ignore list -models/ -config/ -migrations/ -src/helpers/api/installSequelize.ts -src/helpers/installation.ts -src/helpers/models.ts -.sequelizerc +# models/ +# config/ +# migrations/ +# src/helpers/api/installSequelize.ts +# src/helpers/installation.ts +# src/helpers/models.ts +# .sequelizerc diff --git a/.sequelizerc b/.sequelizerc new file mode 100644 index 0000000..3157456 --- /dev/null +++ b/.sequelizerc @@ -0,0 +1,7 @@ +const path = require('path'); + +module.exports = { + env: process.env.NODE_ENV, + 'config': path.resolve('config', 'config.js'), + +} \ No newline at end of file diff --git a/CHANGELOG b/CHANGELOG index 4507a34..1c4f4c9 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,12 @@ +v0.3.0-dev + - Version bumped to 0.3.0 + - NextAuth.js Introduced + - OAuth now works with MMDL! + - Supports Keycloak, Google, Authentik out of the box. The rest (those supported by NextAuth.js) can be added manually by the user. + - Sequelize formally introduced + - Models and migrations generated + - Bug fixes + v0.1.9 - Removed Fullcalendar script import from _app.js - Looks like calendar view works without it. diff --git a/COMMITMESSAGE.md b/COMMITMESSAGE.md index ca25edf..45d6c67 100644 --- a/COMMITMESSAGE.md +++ b/COMMITMESSAGE.md @@ -1,3 +1,8 @@ -admin/getusers API Changes -- Added dev dependencies to make cypress work. -- Added eslint dependencies \ No newline at end of file +v0.3.0-dev + - Version bumped to 0.3.0 + - NextAuth.js Introduced + - OAuth now works with MMDL! + - Supports Keycloak, Google, Authentik out of the box. The rest (those supported by NextAuth.js) can be added manually by the user. + - Sequelize formally introduced + - Models and migrations generated + - Bug fixes \ No newline at end of file diff --git a/config/config.js b/config/config.js new file mode 100644 index 0000000..423dea7 --- /dev/null +++ b/config/config.js @@ -0,0 +1,27 @@ +const dotenv = require('dotenv') +dotenv.config({ path: `.env.local`, override: true }); +module.exports = { + local: { + username: process.env.DB_USER, + password: process.env.DB_PASS, + database: process.env.DB_NAME, + host: process.env.DB_HOST, + port: 3306, + dialect: "mysql" + }, + test: { + username: "root", + password: null, + database: "database_test", + host: "127.0.0.1", + dialect: "mysql" + }, + production: { + username: "root", + password: null, + database: "database_production", + host: "127.0.0.1", + dialect: "mysql" + } +} + diff --git a/config/nextAuthProviders.js b/config/nextAuthProviders.js new file mode 100644 index 0000000..54412e7 --- /dev/null +++ b/config/nextAuthProviders.js @@ -0,0 +1,48 @@ +import KeycloakProvider from "next-auth/providers/keycloak"; +import GoogleProvider from 'next-auth/providers/google' +import AuthentikProvider from 'next-auth/providers/authentik' +import { varNotEmpty } from "@/helpers/general"; + +/** + * Array of authProviders that will be passed to NextAuth.js + */ +const authProviders = [] + +/** + * Add KeyCloak if parameters are defined. + */ +if(varNotEmpty(process.env.KEYCLOAK_CLIENT_ID) && varNotEmpty(process.env.KEYCLOAK_ISSUER_URL) && varNotEmpty(process.env.KEYCLOAK_CLIENT_SECRET)){ + authProviders.push( + KeycloakProvider({ + clientId: process.env.KEYCLOAK_CLIENT_ID, + issuer: process.env.KEYCLOAK_ISSUER_URL, + clientSecret: process.env.KEYCLOAK_CLIENT_SECRET + }), + ) +} + +/** + * Add Google Provider if parameters are defined. +*/ +if(varNotEmpty(process.env.GOOGLE_CLIENT_ID) && varNotEmpty(process.env.GOOGLE_CLIENT_SECRET) ){ + authProviders.push( + GoogleProvider({ + clientId: process.env.GOOGLE_CLIENT_ID, + clientSecret: process.env.GOOGLE_CLIENT_SECRET + }) + ) +} +/** + * Add Authentik Provider if parameters are defined. +*/ +if(varNotEmpty(process.env.AUTHENTIK_CLIENT_ID) && varNotEmpty(process.env.AUTHENTIK_CLIENT_SECRET) && varNotEmpty(process.env.AUTHENTIK_ISSUER)){ + + authProviders.push( + AuthentikProvider({ + clientId: process.env.AUTHENTIK_CLIENT_ID, + clientSecret: process.env.AUTHENTIK_CLIENT_SECRET, + issuer: process.env.AUTHENTIK_ISSUER, + }) + ) +} +export default authProviders \ No newline at end of file diff --git a/cypress/screenshots/install.cy.ts/template spec -- passes (failed).png b/cypress/screenshots/install.cy.ts/template spec -- passes (failed).png new file mode 100644 index 0000000..1d5f87d Binary files /dev/null and b/cypress/screenshots/install.cy.ts/template spec -- passes (failed).png differ diff --git a/cypress/videos/install.cy.ts.mp4 b/cypress/videos/install.cy.ts.mp4 new file mode 100644 index 0000000..e2aed9a Binary files /dev/null and b/cypress/videos/install.cy.ts.mp4 differ diff --git a/migrations/20230728075614-first_migration.js b/migrations/20230728075614-first_migration.js new file mode 100644 index 0000000..3a52146 --- /dev/null +++ b/migrations/20230728075614-first_migration.js @@ -0,0 +1,303 @@ +'use strict'; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up (queryInterface, Sequelize) { + await queryInterface.createTable('users', { + users_id: { + autoIncrement: true, + type: Sequelize.INTEGER, + primaryKey: true + }, + username: { + type: Sequelize.STRING(45), + allowNull: true + }, + email: { + type: Sequelize.STRING(45), + allowNull: true + }, + password: { + type: Sequelize.STRING(1000), + allowNull: true + }, + created: { + type: Sequelize.STRING(45), + allowNull: true + }, + level: { + type: Sequelize.STRING(45), + allowNull: true + }, + userhash: { + type: Sequelize.STRING(1000), + allowNull: true + }, + mobile: { + type: Sequelize.STRING(45), + allowNull: true + } + + }); + + await queryInterface.createTable('caldav_accounts', { + caldav_accounts_id: { + autoIncrement: true, + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true + }, + username: { + type: Sequelize.STRING(45), + allowNull: true + }, + password: { + type: Sequelize.STRING(3000), + allowNull: true + }, + url: { + type: Sequelize.STRING(1000), + allowNull: true + }, + userid: { + type: Sequelize.STRING(45), + allowNull: true + }, + name: { + type: Sequelize.STRING(100), + allowNull: true + }, + authMethod: { + type: Sequelize.STRING(45), + allowNull: true + } + + }) + + await queryInterface.createTable('calendar_events', { + calendar_events_id: { + autoIncrement: true, + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true + }, + url: { + type: Sequelize.STRING(3000), + allowNull: true + }, + etag: { + type: Sequelize.STRING(1000), + allowNull: true + }, + data: { + type: Sequelize.STRING(5000), + allowNull: true + }, + updated: { + type: Sequelize.STRING(45), + allowNull: true + }, + type: { + type: Sequelize.STRING(45), + allowNull: true + }, + calendar_id: { + type: Sequelize.STRING(45), + allowNull: true + }, + deleted: { + type: Sequelize.STRING(45), + allowNull: true + } + + }) + + await queryInterface.createTable('calendars', { + calendars_id: { + autoIncrement: true, + type: Sequelize.BIGINT, + allowNull: false, + primaryKey: true + }, + displayName: { + type: Sequelize.STRING(45), + allowNull: true + }, + url: { + type: Sequelize.STRING(200), + allowNull: true + }, + ctag: { + type: Sequelize.STRING(200), + allowNull: true + }, + description: { + type: Sequelize.STRING(45), + allowNull: true + }, + calendarColor: { + type: Sequelize.STRING(45), + allowNull: true + }, + syncToken: { + type: Sequelize.STRING(200), + allowNull: true + }, + timezone: { + type: Sequelize.STRING(45), + allowNull: true + }, + reports: { + type: Sequelize.STRING(2000), + allowNull: true + }, + resourcetype: { + type: Sequelize.STRING(45), + allowNull: true + }, + caldav_accounts_id: { + type: Sequelize.STRING(45), + allowNull: true + }, + updated: { + type: Sequelize.STRING(45), + allowNull: true + } + }) + + await queryInterface.createTable('custom_filters', { + custom_filters_id: { + autoIncrement: true, + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true + }, + name: { + type: Sequelize.STRING(100), + allowNull: true + }, + filtervalue: { + type: Sequelize.STRING(1000), + allowNull: true + }, + userid: { + type: Sequelize.STRING(45), + allowNull: true + } + + }) + + await queryInterface.createTable('labels', { + labels_id: { + autoIncrement: true, + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true + }, + name: { + type: Sequelize.STRING(45), + allowNull: true + }, + colour: { + type: Sequelize.STRING(45), + allowNull: true + }, + userid: { + type: Sequelize.STRING(45), + allowNull: true + } + }) + + await queryInterface.createTable('otp_table', { + otp_table_id: { + autoIncrement: true, + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true + }, + userid: { + type: Sequelize.STRING(45), + allowNull: true + }, + otp: { + type: Sequelize.STRING(45), + allowNull: true + }, + created: { + type: Sequelize.STRING(45), + allowNull: true + }, + type: { + type: Sequelize.STRING(45), + allowNull: true + }, + reqid: { + type: Sequelize.STRING(2000), + allowNull: true + } + + }) + + await queryInterface.createTable('settings', { + settings_id: { + autoIncrement: true, + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true + }, + name: { + type: Sequelize.STRING(200), + allowNull: true + }, + userid: { + type: Sequelize.STRING(45), + allowNull: true + }, + global: { + type: Sequelize.STRING(45), + allowNull: true + }, + value: { + type: Sequelize.STRING(1000), + allowNull: true + } + + }) + + await queryInterface.createTable('ssid_table', { + ssid_table_id: { + autoIncrement: true, + type: Sequelize.INTEGER, + allowNull: false, + primaryKey: true + }, + userhash: { + type: Sequelize.STRING(1000), + allowNull: true + }, + ssid: { + type: Sequelize.STRING(1000), + allowNull: true + }, + created: { + type: Sequelize.STRING(45), + allowNull: true + } + + }) + + }, + async down (queryInterface, Sequelize) { + await queryInterface.dropTable('users'); + await queryInterface.dropTable('caldav_accounts'); + await queryInterface.dropTable('calendar_events'); + await queryInterface.dropTable('calendars'); + await queryInterface.dropTable('custom_filters'); + await queryInterface.dropTable('labels'); + await queryInterface.dropTable('otp_table'); + await queryInterface.dropTable('settings'); + await queryInterface.dropTable('ssid_table'); + + + } +}; diff --git a/migrations/20230730083903-users-add-columns-nextAuth-v-0.3.0.js b/migrations/20230730083903-users-add-columns-nextAuth-v-0.3.0.js new file mode 100644 index 0000000..8ed0bef --- /dev/null +++ b/migrations/20230730083903-users-add-columns-nextAuth-v-0.3.0.js @@ -0,0 +1,54 @@ +'use strict'; + +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up (queryInterface, Sequelize) { + return queryInterface.sequelize.transaction(t => { + return Promise.all([ + + queryInterface.addColumn("users", "id",{ + type: Sequelize.DataTypes.UUID, + defaultValue: Sequelize.DataTypes.UUIDV4, + + }, + {transaction: t}), + queryInterface.addColumn("users", "expires",{ + type: Sequelize.DataTypes.DATE, + }, {transaction: t}), + queryInterface.addColumn("users", "session_token",{ + type: Sequelize.DataTypes.STRING, + unique: "sessionToken", + }, {transaction: t}), + queryInterface.addColumn("users", "name",{ + type: Sequelize.DataTypes.STRING + }, {transaction: t}), + queryInterface.addColumn("users", "email_verified",{ + type: Sequelize.DataTypes.STRING, + }, {transaction: t}), + queryInterface.addColumn("users", "image",{ + type: Sequelize.DataTypes.STRING, + }, {transaction: t}), + + + + + ]); + }); +}, + + async down (queryInterface, Sequelize) { + return queryInterface.sequelize.transaction(t => { + return Promise.all([ + queryInterface.removeColumn("users", "id",{transaction:t}), + queryInterface.removeColumn("users", "session_token",{transaction:t}), + queryInterface.removeColumn("users", "expires",{transaction:t}), + queryInterface.removeColumn("users", "name",{transaction:t}), + queryInterface.removeColumn("users", "email_verified",{transaction:t}), + queryInterface.removeColumn("users", "image",{transaction:t}) + + + ]) + }) + + } +}; diff --git a/migrations/20230730093908-create-session.js b/migrations/20230730093908-create-session.js new file mode 100644 index 0000000..22b9642 --- /dev/null +++ b/migrations/20230730093908-create-session.js @@ -0,0 +1,38 @@ +'use strict'; +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('sessions', { + id: { + allowNull: false, + primaryKey: true, + defaultValue: Sequelize.UUIDV4, + type: Sequelize.UUID + }, + timestamp: { + type: Sequelize.DATE + }, + expires: { type: Sequelize.DATE, allowNull: false }, + session_token: { + type: Sequelize.STRING, + unique: "sessionToken", + allowNull: false, }, + user_id: { + type: Sequelize.UUID + }, + createdAt: { + allowNull: false, + type: Sequelize.DATE, + defaultValue:Sequelize.fn('now') + }, + updatedAt: { + allowNull: false, + type: Sequelize.DATE, + defaultValue:Sequelize.fn('now') + } + }); + }, + async down(queryInterface, Sequelize) { + await queryInterface.dropTable('sessions'); + } +}; \ No newline at end of file diff --git a/migrations/20230730094838-create-account.js b/migrations/20230730094838-create-account.js new file mode 100644 index 0000000..e4a58ca --- /dev/null +++ b/migrations/20230730094838-create-account.js @@ -0,0 +1,36 @@ +'use strict'; +/** @type {import('sequelize-cli').Migration} */ +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.createTable('accounts', { + id: { + type: Sequelize.UUID, + defaultValue: Sequelize.UUIDV4, + primaryKey: true, + }, + type: { type: Sequelize.STRING, allowNull: false }, + provider: { type: Sequelize.STRING, allowNull: false }, + provider_account_id: { type: Sequelize.STRING, allowNull: false }, + refresh_token: { type: Sequelize.TEXT }, + access_token: { type: Sequelize.TEXT }, + expires_at: { type: Sequelize.INTEGER }, + token_type: { type: Sequelize.STRING }, + scope: { type: Sequelize.STRING }, + id_token: { type: Sequelize.TEXT }, + session_state: { type: Sequelize.STRING }, + user_id: { type: Sequelize.UUID }, + createdAt: { + type: Sequelize.DATE, + defaultValue:Sequelize.fn('now'), + }, + updatedAt: { + type: Sequelize.DATE, + defaultValue:Sequelize.fn('now'), + + } + }); + }, + async down(queryInterface, Sequelize) { + await queryInterface.dropTable('accounts'); + } +}; \ No newline at end of file diff --git a/models/account.js b/models/account.js new file mode 100644 index 0000000..5c7bfea --- /dev/null +++ b/models/account.js @@ -0,0 +1,36 @@ +'use strict'; +const { + Model +} = require('sequelize'); +module.exports = (sequelize, DataTypes) => { + class Account extends Model { + /** + * Helper method for defining associations. + * This method is not a part of Sequelize lifecycle. + * The `models/index` file will call this method automatically. + */ + static associate(models) { + // define association here + } + } + Account.init({ + id: DataTypes.UUID, + user_id: DataTypes.UUID, + type: DataTypes.STRING, + provider: DataTypes.STRING, + provider_account_id: DataTypes.STRING, + refresh_token: DataTypes.TEXT, + access_token: DataTypes.TEXT, + expires_at: DataTypes.NUMBER, + token_type: DataTypes.STRING, + scope: DataTypes.STRING, + id_token: DataTypes.TEXT, + session_state: DataTypes.STRING, + createdAt:DataTypes.DATE, + updatedAt:DataTypes.DATE + }, { + sequelize, + modelName: 'account', + }); + return Account; +}; \ No newline at end of file diff --git a/models/caldav_accounts.ts b/models/caldav_accounts.ts new file mode 100644 index 0000000..d249e79 --- /dev/null +++ b/models/caldav_accounts.ts @@ -0,0 +1,77 @@ +import * as Sequelize from 'sequelize'; +import { DataTypes, Model, Optional } from 'sequelize'; + +export interface caldav_accountsAttributes { + caldav_accounts_id: number; + username?: string; + password?: string; + url?: string; + userid?: string; + name?: string; + authMethod?: string; +} + +export type caldav_accountsPk = "caldav_accounts_id"; +export type caldav_accountsId = caldav_accounts[caldav_accountsPk]; +export type caldav_accountsOptionalAttributes = "caldav_accounts_id" | "username" | "password" | "url" | "userid" | "name" | "authMethod"; +export type caldav_accountsCreationAttributes = Optional; + +export class caldav_accounts extends Model implements caldav_accountsAttributes { + caldav_accounts_id!: number; + username?: string; + password?: string; + url?: string; + userid?: string; + name?: string; + authMethod?: string; + + + static initModel(sequelize: Sequelize.Sequelize): typeof caldav_accounts { + return caldav_accounts.init({ + caldav_accounts_id: { + autoIncrement: true, + type: DataTypes.INTEGER, + allowNull: false, + primaryKey: true + }, + username: { + type: DataTypes.STRING(45), + allowNull: true + }, + password: { + type: DataTypes.STRING(3000), + allowNull: true + }, + url: { + type: DataTypes.STRING(1000), + allowNull: true + }, + userid: { + type: DataTypes.STRING(45), + allowNull: true + }, + name: { + type: DataTypes.STRING(100), + allowNull: true + }, + authMethod: { + type: DataTypes.STRING(45), + allowNull: true + } + }, { + sequelize, + tableName: 'caldav_accounts', + timestamps: false, + indexes: [ + { + name: "PRIMARY", + unique: true, + using: "BTREE", + fields: [ + { name: "caldav_accounts_id" }, + ] + }, + ] + }); + } +} diff --git a/models/calendar_events.ts b/models/calendar_events.ts new file mode 100644 index 0000000..945ccb0 --- /dev/null +++ b/models/calendar_events.ts @@ -0,0 +1,83 @@ +import * as Sequelize from 'sequelize'; +import { DataTypes, Model, Optional } from 'sequelize'; + +export interface calendar_eventsAttributes { + calendar_events_id: number; + url?: string; + etag?: string; + data?: string; + updated?: string; + type?: string; + calendar_id?: string; + deleted?: string; +} + +export type calendar_eventsPk = "calendar_events_id"; +export type calendar_eventsId = calendar_events[calendar_eventsPk]; +export type calendar_eventsOptionalAttributes = "calendar_events_id" | "url" | "etag" | "data" | "updated" | "type" | "calendar_id" | "deleted"; +export type calendar_eventsCreationAttributes = Optional; + +export class calendar_events extends Model implements calendar_eventsAttributes { + calendar_events_id!: number; + url?: string; + etag?: string; + data?: string; + updated?: string; + type?: string; + calendar_id?: string; + deleted?: string; + + + static initModel(sequelize: Sequelize.Sequelize): typeof calendar_events { + return calendar_events.init({ + calendar_events_id: { + autoIncrement: true, + type: DataTypes.INTEGER, + allowNull: false, + primaryKey: true + }, + url: { + type: DataTypes.STRING(3000), + allowNull: true + }, + etag: { + type: DataTypes.STRING(1000), + allowNull: true + }, + data: { + type: DataTypes.STRING(5000), + allowNull: true + }, + updated: { + type: DataTypes.STRING(45), + allowNull: true + }, + type: { + type: DataTypes.STRING(45), + allowNull: true + }, + calendar_id: { + type: DataTypes.STRING(45), + allowNull: true + }, + deleted: { + type: DataTypes.STRING(45), + allowNull: true + } + }, { + sequelize, + tableName: 'calendar_events', + timestamps: false, + indexes: [ + { + name: "PRIMARY", + unique: true, + using: "BTREE", + fields: [ + { name: "calendar_events_id" }, + ] + }, + ] + }); + } +} diff --git a/models/calendars.ts b/models/calendars.ts new file mode 100644 index 0000000..80fd980 --- /dev/null +++ b/models/calendars.ts @@ -0,0 +1,107 @@ +import * as Sequelize from 'sequelize'; +import { DataTypes, Model, Optional } from 'sequelize'; + +export interface calendarsAttributes { + calendars_id: number; + displayName?: string; + url?: string; + ctag?: string; + description?: string; + calendarColor?: string; + syncToken?: string; + timezone?: string; + reports?: string; + resourcetype?: string; + caldav_accounts_id?: string; + updated?: string; +} + +export type calendarsPk = "calendars_id"; +export type calendarsId = calendars[calendarsPk]; +export type calendarsOptionalAttributes = "calendars_id" | "displayName" | "url" | "ctag" | "description" | "calendarColor" | "syncToken" | "timezone" | "reports" | "resourcetype" | "caldav_accounts_id" | "updated"; +export type calendarsCreationAttributes = Optional; + +export class calendars extends Model implements calendarsAttributes { + calendars_id!: number; + displayName?: string; + url?: string; + ctag?: string; + description?: string; + calendarColor?: string; + syncToken?: string; + timezone?: string; + reports?: string; + resourcetype?: string; + caldav_accounts_id?: string; + updated?: string; + + + static initModel(sequelize: Sequelize.Sequelize): typeof calendars { + return calendars.init({ + calendars_id: { + autoIncrement: true, + type: DataTypes.BIGINT, + allowNull: false, + primaryKey: true + }, + displayName: { + type: DataTypes.STRING(45), + allowNull: true + }, + url: { + type: DataTypes.STRING(200), + allowNull: true + }, + ctag: { + type: DataTypes.STRING(200), + allowNull: true + }, + description: { + type: DataTypes.STRING(45), + allowNull: true + }, + calendarColor: { + type: DataTypes.STRING(45), + allowNull: true + }, + syncToken: { + type: DataTypes.STRING(200), + allowNull: true + }, + timezone: { + type: DataTypes.STRING(45), + allowNull: true + }, + reports: { + type: DataTypes.STRING(2000), + allowNull: true + }, + resourcetype: { + type: DataTypes.STRING(45), + allowNull: true + }, + caldav_accounts_id: { + type: DataTypes.STRING(45), + allowNull: true + }, + updated: { + type: DataTypes.STRING(45), + allowNull: true + } + }, { + sequelize, + tableName: 'calendars', + timestamps: false, + indexes: [ + { + name: "PRIMARY", + unique: true, + using: "BTREE", + fields: [ + { name: "calendars_id" }, + ] + }, + ] + }); + } +} diff --git a/models/custom_filters.ts b/models/custom_filters.ts new file mode 100644 index 0000000..076135f --- /dev/null +++ b/models/custom_filters.ts @@ -0,0 +1,59 @@ +import * as Sequelize from 'sequelize'; +import { DataTypes, Model, Optional } from 'sequelize'; + +export interface custom_filtersAttributes { + custom_filters_id: number; + name?: string; + filtervalue?: string; + userid?: string; +} + +export type custom_filtersPk = "custom_filters_id"; +export type custom_filtersId = custom_filters[custom_filtersPk]; +export type custom_filtersOptionalAttributes = "custom_filters_id" | "name" | "filtervalue" | "userid"; +export type custom_filtersCreationAttributes = Optional; + +export class custom_filters extends Model implements custom_filtersAttributes { + custom_filters_id!: number; + name?: string; + filtervalue?: string; + userid?: string; + + + static initModel(sequelize: Sequelize.Sequelize): typeof custom_filters { + return custom_filters.init({ + custom_filters_id: { + autoIncrement: true, + type: DataTypes.INTEGER, + allowNull: false, + primaryKey: true + }, + name: { + type: DataTypes.STRING(100), + allowNull: true + }, + filtervalue: { + type: DataTypes.STRING(1000), + allowNull: true + }, + userid: { + type: DataTypes.STRING(45), + allowNull: true + } + }, { + sequelize, + tableName: 'custom_filters', + timestamps: false, + indexes: [ + { + name: "PRIMARY", + unique: true, + using: "BTREE", + fields: [ + { name: "custom_filters_id" }, + ] + }, + ] + }); + } +} diff --git a/models/index.js b/models/index.js new file mode 100644 index 0000000..024200e --- /dev/null +++ b/models/index.js @@ -0,0 +1,43 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const Sequelize = require('sequelize'); +const process = require('process'); +const basename = path.basename(__filename); +const env = process.env.NODE_ENV || 'development'; +const config = require(__dirname + '/../config/config.json')[env]; +const db = {}; + +let sequelize; +if (config.use_env_variable) { + sequelize = new Sequelize(process.env[config.use_env_variable], config); +} else { + sequelize = new Sequelize(config.database, config.username, config.password, config); +} + +fs + .readdirSync(__dirname) + .filter(file => { + return ( + file.indexOf('.') !== 0 && + file !== basename && + file.slice(-3) === '.js' && + file.indexOf('.test.js') === -1 + ); + }) + .forEach(file => { + const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes); + db[model.name] = model; + }); + +Object.keys(db).forEach(modelName => { + if (db[modelName].associate) { + db[modelName].associate(db); + } +}); + +db.sequelize = sequelize; +db.Sequelize = Sequelize; + +module.exports = db; diff --git a/models/init-models.ts b/models/init-models.ts new file mode 100644 index 0000000..81c389e --- /dev/null +++ b/models/init-models.ts @@ -0,0 +1,77 @@ +import type { Sequelize } from "sequelize"; +import { caldav_accounts as _caldav_accounts } from "./caldav_accounts"; +import type { caldav_accountsAttributes, caldav_accountsCreationAttributes } from "./caldav_accounts"; +import { calendar_events as _calendar_events } from "./calendar_events"; +import type { calendar_eventsAttributes, calendar_eventsCreationAttributes } from "./calendar_events"; +import { calendars as _calendars } from "./calendars"; +import type { calendarsAttributes, calendarsCreationAttributes } from "./calendars"; +import { custom_filters as _custom_filters } from "./custom_filters"; +import type { custom_filtersAttributes, custom_filtersCreationAttributes } from "./custom_filters"; +import { labels as _labels } from "./labels"; +import type { labelsAttributes, labelsCreationAttributes } from "./labels"; +import { otp_table as _otp_table } from "./otp_table"; +import type { otp_tableAttributes, otp_tableCreationAttributes } from "./otp_table"; +import { settings as _settings } from "./settings"; +import type { settingsAttributes, settingsCreationAttributes } from "./settings"; +import { ssid_table as _ssid_table } from "./ssid_table"; +import type { ssid_tableAttributes, ssid_tableCreationAttributes } from "./ssid_table"; +import { users as _users } from "./users"; +import type { usersAttributes, usersCreationAttributes } from "./users"; + +export { + _caldav_accounts as caldav_accounts, + _calendar_events as calendar_events, + _calendars as calendars, + _custom_filters as custom_filters, + _labels as labels, + _otp_table as otp_table, + _settings as settings, + _ssid_table as ssid_table, + _users as users, +}; + +export type { + caldav_accountsAttributes, + caldav_accountsCreationAttributes, + calendar_eventsAttributes, + calendar_eventsCreationAttributes, + calendarsAttributes, + calendarsCreationAttributes, + custom_filtersAttributes, + custom_filtersCreationAttributes, + labelsAttributes, + labelsCreationAttributes, + otp_tableAttributes, + otp_tableCreationAttributes, + settingsAttributes, + settingsCreationAttributes, + ssid_tableAttributes, + ssid_tableCreationAttributes, + usersAttributes, + usersCreationAttributes, +}; + +export function initModels(sequelize: Sequelize) { + const caldav_accounts = _caldav_accounts.initModel(sequelize); + const calendar_events = _calendar_events.initModel(sequelize); + const calendars = _calendars.initModel(sequelize); + const custom_filters = _custom_filters.initModel(sequelize); + const labels = _labels.initModel(sequelize); + const otp_table = _otp_table.initModel(sequelize); + const settings = _settings.initModel(sequelize); + const ssid_table = _ssid_table.initModel(sequelize); + const users = _users.initModel(sequelize); + + + return { + caldav_accounts: caldav_accounts, + calendar_events: calendar_events, + calendars: calendars, + custom_filters: custom_filters, + labels: labels, + otp_table: otp_table, + settings: settings, + ssid_table: ssid_table, + users: users, + }; +} diff --git a/models/labels.ts b/models/labels.ts new file mode 100644 index 0000000..b741fe1 --- /dev/null +++ b/models/labels.ts @@ -0,0 +1,59 @@ +import * as Sequelize from 'sequelize'; +import { DataTypes, Model, Optional } from 'sequelize'; + +export interface labelsAttributes { + labels_id: number; + name?: string; + colour?: string; + userid?: string; +} + +export type labelsPk = "labels_id"; +export type labelsId = labels[labelsPk]; +export type labelsOptionalAttributes = "labels_id" | "name" | "colour" | "userid"; +export type labelsCreationAttributes = Optional; + +export class labels extends Model implements labelsAttributes { + labels_id!: number; + name?: string; + colour?: string; + userid?: string; + + + static initModel(sequelize: Sequelize.Sequelize): typeof labels { + return labels.init({ + labels_id: { + autoIncrement: true, + type: DataTypes.INTEGER, + allowNull: false, + primaryKey: true + }, + name: { + type: DataTypes.STRING(45), + allowNull: true + }, + colour: { + type: DataTypes.STRING(45), + allowNull: true + }, + userid: { + type: DataTypes.STRING(45), + allowNull: true + } + }, { + sequelize, + tableName: 'labels', + timestamps: false, + indexes: [ + { + name: "PRIMARY", + unique: true, + using: "BTREE", + fields: [ + { name: "labels_id" }, + ] + }, + ] + }); + } +} diff --git a/models/otp_table.ts b/models/otp_table.ts new file mode 100644 index 0000000..19f5968 --- /dev/null +++ b/models/otp_table.ts @@ -0,0 +1,71 @@ +import * as Sequelize from 'sequelize'; +import { DataTypes, Model, Optional } from 'sequelize'; + +export interface otp_tableAttributes { + otp_table_id: number; + userid?: string; + otp?: string; + created?: string; + type?: string; + reqid?: string; +} + +export type otp_tablePk = "otp_table_id"; +export type otp_tableId = otp_table[otp_tablePk]; +export type otp_tableOptionalAttributes = "otp_table_id" | "userid" | "otp" | "created" | "type" | "reqid"; +export type otp_tableCreationAttributes = Optional; + +export class otp_table extends Model implements otp_tableAttributes { + otp_table_id!: number; + userid?: string; + otp?: string; + created?: string; + type?: string; + reqid?: string; + + + static initModel(sequelize: Sequelize.Sequelize): typeof otp_table { + return otp_table.init({ + otp_table_id: { + autoIncrement: true, + type: DataTypes.INTEGER, + allowNull: false, + primaryKey: true + }, + userid: { + type: DataTypes.STRING(45), + allowNull: true + }, + otp: { + type: DataTypes.STRING(45), + allowNull: true + }, + created: { + type: DataTypes.STRING(45), + allowNull: true + }, + type: { + type: DataTypes.STRING(45), + allowNull: true + }, + reqid: { + type: DataTypes.STRING(2000), + allowNull: true + } + }, { + sequelize, + tableName: 'otp_table', + timestamps: false, + indexes: [ + { + name: "PRIMARY", + unique: true, + using: "BTREE", + fields: [ + { name: "otp_table_id" }, + ] + }, + ] + }); + } +} diff --git a/models/session.js b/models/session.js new file mode 100644 index 0000000..e3b9628 --- /dev/null +++ b/models/session.js @@ -0,0 +1,22 @@ +'use strict'; +const { + Model +} = require('sequelize'); +module.exports = (sequelize, DataTypes) => { + class Session extends Model { + static associate(models) { + // define association here + } + } + Session.init({ + id: DataTypes.UUID, + expires:DataTypes.DATE, + timestamp: DataTypes.DATE, + session_token: DataTypes.STRING, + user_id: DataTypes.UUID + }, { + sequelize, + modelName: 'session', + }); + return Session; +}; \ No newline at end of file diff --git a/models/settings.ts b/models/settings.ts new file mode 100644 index 0000000..b09dfdc --- /dev/null +++ b/models/settings.ts @@ -0,0 +1,65 @@ +import * as Sequelize from 'sequelize'; +import { DataTypes, Model, Optional } from 'sequelize'; + +export interface settingsAttributes { + settings_id: number; + name?: string; + userid?: string; + global?: string; + value?: string; +} + +export type settingsPk = "settings_id"; +export type settingsId = settings[settingsPk]; +export type settingsOptionalAttributes = "settings_id" | "name" | "userid" | "global" | "value"; +export type settingsCreationAttributes = Optional; + +export class settings extends Model implements settingsAttributes { + settings_id!: number; + name?: string; + userid?: string; + global?: string; + value?: string; + + + static initModel(sequelize: Sequelize.Sequelize): typeof settings { + return settings.init({ + settings_id: { + autoIncrement: true, + type: DataTypes.INTEGER, + allowNull: false, + primaryKey: true + }, + name: { + type: DataTypes.STRING(200), + allowNull: true + }, + userid: { + type: DataTypes.STRING(45), + allowNull: true + }, + global: { + type: DataTypes.STRING(45), + allowNull: true + }, + value: { + type: DataTypes.STRING(1000), + allowNull: true + } + }, { + sequelize, + tableName: 'settings', + timestamps: false, + indexes: [ + { + name: "PRIMARY", + unique: true, + using: "BTREE", + fields: [ + { name: "settings_id" }, + ] + }, + ] + }); + } +} diff --git a/models/ssid_table.ts b/models/ssid_table.ts new file mode 100644 index 0000000..1c46f97 --- /dev/null +++ b/models/ssid_table.ts @@ -0,0 +1,59 @@ +import * as Sequelize from 'sequelize'; +import { DataTypes, Model, Optional } from 'sequelize'; + +export interface ssid_tableAttributes { + ssid_table_id: number; + userhash?: string; + ssid?: string; + created?: string; +} + +export type ssid_tablePk = "ssid_table_id"; +export type ssid_tableId = ssid_table[ssid_tablePk]; +export type ssid_tableOptionalAttributes = "ssid_table_id" | "userhash" | "ssid" | "created"; +export type ssid_tableCreationAttributes = Optional; + +export class ssid_table extends Model implements ssid_tableAttributes { + ssid_table_id!: number; + userhash?: string; + ssid?: string; + created?: string; + + + static initModel(sequelize: Sequelize.Sequelize): typeof ssid_table { + return ssid_table.init({ + ssid_table_id: { + autoIncrement: true, + type: DataTypes.INTEGER, + allowNull: false, + primaryKey: true + }, + userhash: { + type: DataTypes.STRING(1000), + allowNull: true + }, + ssid: { + type: DataTypes.STRING(1000), + allowNull: true + }, + created: { + type: DataTypes.STRING(45), + allowNull: true + } + }, { + sequelize, + tableName: 'ssid_table', + timestamps: false, + indexes: [ + { + name: "PRIMARY", + unique: true, + using: "BTREE", + fields: [ + { name: "ssid_table_id" }, + ] + }, + ] + }); + } +} diff --git a/models/users.ts b/models/users.ts new file mode 100644 index 0000000..bebeeb1 --- /dev/null +++ b/models/users.ts @@ -0,0 +1,119 @@ +import * as Sequelize from 'sequelize'; +import { DataTypes, Model, Optional } from 'sequelize'; + +export interface usersAttributes { + users_id: number; + username?: string; + email?: string; + password?: string; + created?: string; + level?: string; + userhash?: string; + mobile?: string; + id?: number; + expires?:Date; + session_token?:string; + name?:string; + email_verified?:string; + image?:string + +} + +export type usersPk = "users_id"; +export type usersId = users[usersPk]; +export type usersOptionalAttributes = "users_id" | "username" | "email" | "password" | "created" | "level" | "userhash" | "mobile"; +export type usersCreationAttributes = Optional; + +export class users extends Model implements usersAttributes { + users_id!: number; + username?: string; + email?: string; + password?: string; + created?: string; + level?: string; + userhash?: string; + mobile?: string; + id?: number; + expires?:Date; + session_token?:string; + name?:string; + email_verified?:string; + image?:string + + + static initModel(sequelize: Sequelize.Sequelize): typeof users { + return users.init({ + users_id: { + autoIncrement: true, + type: DataTypes.INTEGER, + primaryKey: true + }, + username: { + type: DataTypes.STRING(45), + allowNull: true + }, + email: { + type: DataTypes.STRING(45), + allowNull: true + }, + password: { + type: DataTypes.STRING(1000), + allowNull: true + }, + created: { + type: DataTypes.STRING(45), + allowNull: true + }, + level: { + type: DataTypes.STRING(45), + allowNull: true + }, + userhash: { + type: DataTypes.STRING(1000), + allowNull: true + }, + mobile: { + type: DataTypes.STRING(45), + allowNull: true + }, + id:{ + type: DataTypes.UUID, + defaultValue: DataTypes.UUIDV4, + + }, + expires:{ + type: Sequelize.DataTypes.DATE, + + }, + session_token:{ + type: Sequelize.DataTypes.STRING, + unique: "sessionToken", + }, + name:{ + type: Sequelize.DataTypes.STRING + }, + email_verified:{ + type: Sequelize.DataTypes.STRING, + }, + image:{ + type: Sequelize.DataTypes.STRING, + + } + + }, { + sequelize, + tableName: 'users', + timestamps: false, + indexes: [ + { + name: "PRIMARY", + unique: true, + using: "BTREE", + fields: [ + { name: "users_id" }, + ] + }, + ] + }); + } +} diff --git a/package-lock.json b/package-lock.json index a53f3fb..488e56c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,13 +1,14 @@ { "name": "manage-my-damn-life-nextjs", - "version": "0.2.0", + "version": "0.3.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "manage-my-damn-life-nextjs", - "version": "0.2.0", + "version": "0.3.0", "dependencies": { + "@auth/sequelize-adapter": "1.0.1", "@babel/core": "7.21.8", "@emotion/react": "11.10.6", "@emotion/styled": "11.10.6", @@ -39,11 +40,13 @@ "ical.js": "1.5.0", "js-base64": "3.7.5", "js-cookie": "3.0.1", + "keycloak-js": "22.0.1", "lodash": "4.17.21", "moment": "2.29.4", "mysql": "2.18.1", "mysql2": "3.4.0", "next": "13.2.4", + "next-auth": "4.22.3", "nextjs-progressbar": "0.0.16", "nodemailer": "6.9.1", "popper.js": "1.16.1", @@ -98,6 +101,58 @@ "node": ">=6.0.0" } }, + "node_modules/@auth/core": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/@auth/core/-/core-0.8.3.tgz", + "integrity": "sha512-lbpMRk36uhBrfJFL77YEPu9tOLI0XtcjZ4nYBzebcadliHeQITIilQGLbZ107hKMI0rfX3tOEbyybgdOtJHjxw==", + "dependencies": { + "@panva/hkdf": "^1.0.4", + "cookie": "0.5.0", + "jose": "^4.11.1", + "oauth4webapi": "^2.0.6", + "preact": "10.11.3", + "preact-render-to-string": "5.2.3" + }, + "peerDependencies": { + "nodemailer": "^6.8.0" + }, + "peerDependenciesMeta": { + "nodemailer": { + "optional": true + } + } + }, + "node_modules/@auth/core/node_modules/preact": { + "version": "10.11.3", + "resolved": "https://registry.npmjs.org/preact/-/preact-10.11.3.tgz", + "integrity": "sha512-eY93IVpod/zG3uMF22Unl8h9KkrcKIRs2EGar8hwLZZDU1lkjph303V9HZBwufh2s736U6VXuhD109LYqPoffg==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/preact" + } + }, + "node_modules/@auth/core/node_modules/preact-render-to-string": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-5.2.3.tgz", + "integrity": "sha512-aPDxUn5o3GhWdtJtW0svRC2SS/l8D9MAgo2+AWml+BhDImb27ALf04Q2d+AHqUUOc6RdSXFIBVa2gxzgMKgtZA==", + "dependencies": { + "pretty-format": "^3.8.0" + }, + "peerDependencies": { + "preact": ">=10" + } + }, + "node_modules/@auth/sequelize-adapter": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@auth/sequelize-adapter/-/sequelize-adapter-1.0.1.tgz", + "integrity": "sha512-BePsH+pKOb08tHFNY4Q3/S9jLWdPPKvlJuITMGAdSC/rUgE6x3lk1BYsEBgVZGwcS0Fczlv/xdjTcmF8/kh5gg==", + "dependencies": { + "@auth/core": "0.8.3" + }, + "peerDependencies": { + "sequelize": "^6.6.5" + } + }, "node_modules/@babel/code-frame": { "version": "7.22.5", "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.22.5.tgz", @@ -2915,6 +2970,14 @@ "node": ">= 8" } }, + "node_modules/@panva/hkdf": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/@panva/hkdf/-/hkdf-1.1.1.tgz", + "integrity": "sha512-dhPeilub1NuIG0X5Kvhh9lH4iW3ZsHlnzwgwbOlgwQ2wG1IqFzsgHqmKPk3WzsdWAeaxKJxgM0+W433RmN45GA==", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/@pkgr/utils": { "version": "2.4.2", "resolved": "https://registry.npmjs.org/@pkgr/utils/-/utils-2.4.2.tgz", @@ -3665,7 +3728,6 @@ "version": "1.5.1", "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.5.1.tgz", "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==", - "dev": true, "funding": [ { "type": "github", @@ -4173,6 +4235,14 @@ "version": "1.9.0", "license": "MIT" }, + "node_modules/cookie": { + "version": "0.5.0", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.5.0.tgz", + "integrity": "sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==", + "engines": { + "node": ">= 0.6" + } + }, "node_modules/core-js-compat": { "version": "3.31.1", "resolved": "https://registry.npmjs.org/core-js-compat/-/core-js-compat-3.31.1.tgz", @@ -7258,6 +7328,14 @@ "integrity": "sha512-Yljz7ffyPbrLpLngrMtZ7NduUgVvi6wG9RJ9IUcyCd59YQ911PBJphODUcbOVbqYfxe1wuYf/LJ8PauMRwsM/g==", "dev": true }, + "node_modules/jose": { + "version": "4.14.4", + "resolved": "https://registry.npmjs.org/jose/-/jose-4.14.4.tgz", + "integrity": "sha512-j8GhLiKmUAh+dsFXlX1aJCbt5KMibuKb+d7j1JaOJG6s2UjX1PQlW+OKB/sD4a/5ZYF4RcmYmLSndOoU3Lt/3g==", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/js-base64": { "version": "3.7.5", "license": "BSD-3-Clause" @@ -7288,6 +7366,11 @@ "node": ">=12" } }, + "node_modules/js-sha256": { + "version": "0.9.0", + "resolved": "https://registry.npmjs.org/js-sha256/-/js-sha256-0.9.0.tgz", + "integrity": "sha512-sga3MHh9sgQN2+pJ9VYZ+1LPwXOxuBJBA5nrR5/ofPfuiJBE2hnjsaN8se8JznOmGLN2p49Pe5U/ttafcs/apA==" + }, "node_modules/js-tokens": { "version": "4.0.0", "license": "MIT" @@ -7387,6 +7470,15 @@ "node": ">=4.0" } }, + "node_modules/keycloak-js": { + "version": "22.0.1", + "resolved": "https://registry.npmjs.org/keycloak-js/-/keycloak-js-22.0.1.tgz", + "integrity": "sha512-5cwOzMTMW2HuKGaIHv50BJHz2o8ID+YgzaaXKNwOk0XqD6ZOPD/jQXvqTz+Z8ID5cP46zVWnNiTouFK41NbPOQ==", + "dependencies": { + "base64-js": "^1.5.1", + "js-sha256": "^0.9.0" + } + }, "node_modules/language-subtag-registry": { "version": "0.3.22", "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.22.tgz", @@ -8033,6 +8125,33 @@ } } }, + "node_modules/next-auth": { + "version": "4.22.3", + "resolved": "https://registry.npmjs.org/next-auth/-/next-auth-4.22.3.tgz", + "integrity": "sha512-XAgy9xV3J2eJOXrQhmxdjV6MLM29ibm6WtMXc3KY6IPZeApf+SuBuPvlqCUfbu5YsAzlg9WSw6u01dChTfeZOA==", + "dependencies": { + "@babel/runtime": "^7.20.13", + "@panva/hkdf": "^1.0.2", + "cookie": "^0.5.0", + "jose": "^4.11.4", + "oauth": "^0.9.15", + "openid-client": "^5.4.0", + "preact": "^10.6.3", + "preact-render-to-string": "^5.1.19", + "uuid": "^8.3.2" + }, + "peerDependencies": { + "next": "^12.2.5 || ^13", + "nodemailer": "^6.6.5", + "react": "^17.0.2 || ^18", + "react-dom": "^17.0.2 || ^18" + }, + "peerDependenciesMeta": { + "nodemailer": { + "optional": true + } + } + }, "node_modules/next-tick": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/next-tick/-/next-tick-1.1.0.tgz", @@ -8152,6 +8271,19 @@ "url": "https://github.com/fb55/nth-check?sponsor=1" } }, + "node_modules/oauth": { + "version": "0.9.15", + "resolved": "https://registry.npmjs.org/oauth/-/oauth-0.9.15.tgz", + "integrity": "sha512-a5ERWK1kh38ExDEfoO6qUHJb32rd7aYmPHuyCu3Fta/cnICvYmgd2uhuKXvPD+PXB+gCEYYEaQdIRAjCOwAKNA==" + }, + "node_modules/oauth4webapi": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/oauth4webapi/-/oauth4webapi-2.3.0.tgz", + "integrity": "sha512-JGkb5doGrwzVDuHwgrR4nHJayzN4h59VCed6EW8Tql6iHDfZIabCJvg6wtbn5q6pyB2hZruI3b77Nudvq7NmvA==", + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, "node_modules/object-assign": { "version": "4.1.1", "license": "MIT", @@ -8159,6 +8291,14 @@ "node": ">=0.10.0" } }, + "node_modules/object-hash": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz", + "integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==", + "engines": { + "node": ">= 6" + } + }, "node_modules/object-inspect": { "version": "1.12.3", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.12.3.tgz", @@ -8256,6 +8396,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/oidc-token-hash": { + "version": "5.0.3", + "resolved": "https://registry.npmjs.org/oidc-token-hash/-/oidc-token-hash-5.0.3.tgz", + "integrity": "sha512-IF4PcGgzAr6XXSff26Sk/+P4KZFJVuHAJZj3wgO3vX2bMdNVp/QXTP3P7CEm9V1IdG8lDLY3HhiqpsE/nOwpPw==", + "engines": { + "node": "^10.13.0 || >=12.0.0" + } + }, "node_modules/once": { "version": "1.4.0", "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", @@ -8297,6 +8445,36 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/openid-client": { + "version": "5.4.3", + "resolved": "https://registry.npmjs.org/openid-client/-/openid-client-5.4.3.tgz", + "integrity": "sha512-sVQOvjsT/sbSfYsQI/9liWQGVZH/Pp3rrtlGEwgk/bbHfrUDZ24DN57lAagIwFtuEu+FM9Ev7r85s8S/yPjimQ==", + "dependencies": { + "jose": "^4.14.4", + "lru-cache": "^6.0.0", + "object-hash": "^2.2.0", + "oidc-token-hash": "^5.0.3" + }, + "funding": { + "url": "https://github.com/sponsors/panva" + } + }, + "node_modules/openid-client/node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/openid-client/node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, "node_modules/optionator": { "version": "0.9.3", "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.3.tgz", @@ -8996,6 +9174,17 @@ "url": "https://opencollective.com/preact" } }, + "node_modules/preact-render-to-string": { + "version": "5.2.6", + "resolved": "https://registry.npmjs.org/preact-render-to-string/-/preact-render-to-string-5.2.6.tgz", + "integrity": "sha512-JyhErpYOvBV1hEPwIxc/fHWXPfnEGdRKxc8gFdAZ7XV4tlzyzG847XAyEZqoDnynP88akM4eaHcSOzNcLWFguw==", + "dependencies": { + "pretty-format": "^3.8.0" + }, + "peerDependencies": { + "preact": ">=10" + } + }, "node_modules/prelude-ls": { "version": "1.2.1", "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", @@ -9017,6 +9206,11 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/pretty-format": { + "version": "3.8.0", + "resolved": "https://registry.npmjs.org/pretty-format/-/pretty-format-3.8.0.tgz", + "integrity": "sha512-WuxUnVtlWL1OfZFQFuqvnvs6MiAGk9UNsBostyBOB0Is9wb5uRESevA6rnl/rkksXaGX3GzZhPup5d6Vp1nFew==" + }, "node_modules/process-nextick-args": { "version": "2.0.1", "license": "MIT" diff --git a/package.json b/package.json index 938ca18..64f8acd 100644 --- a/package.json +++ b/package.json @@ -1,15 +1,18 @@ { "name": "manage-my-damn-life-nextjs", - "version": "0.2.0", + "version": "0.3.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start", "lint": "next lint", + "migrate": "npx sequelize-cli db:migrate --env local", + "undo-migrate": "npx sequelize-cli db:migrate:undo --env local", "cypress": "cypress open" }, "dependencies": { + "@auth/sequelize-adapter": "1.0.1", "@babel/core": "7.21.8", "@emotion/react": "11.10.6", "@emotion/styled": "11.10.6", @@ -41,11 +44,13 @@ "ical.js": "1.5.0", "js-base64": "3.7.5", "js-cookie": "3.0.1", + "keycloak-js": "22.0.1", "lodash": "4.17.21", "moment": "2.29.4", "mysql": "2.18.1", "mysql2": "3.4.0", "next": "13.2.4", + "next-auth": "4.22.3", "nextjs-progressbar": "0.0.16", "nodemailer": "6.9.1", "popper.js": "1.16.1", diff --git a/src/components/Home/HomeTasks/HomeTasks.tsx b/src/components/Home/HomeTasks/HomeTasks.tsx index ec66f06..a53ee7e 100644 --- a/src/components/Home/HomeTasks/HomeTasks.tsx +++ b/src/components/Home/HomeTasks/HomeTasks.tsx @@ -1,5 +1,4 @@ import { getI18nObject } from "@/helpers/frontend/general"; -import { withRouter } from "next/router"; import React, { FC, ReactElement, useEffect, useState } from 'react'; import TaskList from "../../tasks/TaskList"; import { getTodaysDateUnixTimeStamp, varNotEmpty } from "@/helpers/general"; @@ -7,6 +6,7 @@ import { MYDAY_LABEL } from "@/config/constants"; import Form from 'react-bootstrap/Form'; import { refreshMenuOptionsFromServer } from "./HomeTasksFunctions"; import { isValidFilter } from "@/helpers/frontend/filters"; +import * as _ from 'lodash' interface homeTasksPropsInterface { router: object @@ -52,7 +52,11 @@ function HomeTasks(props:homeTasksPropsInterface) { useEffect( () => { const refreshMenuOptions = async () =>{ const newMenuOptions = await refreshMenuOptionsFromServer(menuOptions) - setMenuOptions(newMenuOptions) + //console.log(menuOptions, newMenuOptions) + if(_.isEqual(menuOptions, newMenuOptions) ==false){ + setMenuOptions(newMenuOptions) + + } } refreshMenuOptions() }, [updated, menuOptions]) diff --git a/src/components/LabelManager.js b/src/components/LabelManager.js index 341f1ba..7e03590 100644 --- a/src/components/LabelManager.js +++ b/src/components/LabelManager.js @@ -157,20 +157,13 @@ class LabelManager extends Component{ }else{ var message= getMessageFromAPIResponse(body) + console.error("getLabelsFromServer", message, body) + if(message!=null) { - if(message=="PLEASE_LOGIN") + if(message!=="PLEASE_LOGIN") { - // Login required - var redirectURL="/login" - if(window!=undefined) - { - - - redirectURL +="?redirect="+window.location.pathname - } - this.props.router.push(redirectURL) - + toast.error(this.i18next.t(message)) } } diff --git a/src/components/common/AppBarGeneric.js b/src/components/common/AppBar/AppBarGenericClass.js similarity index 89% rename from src/components/common/AppBarGeneric.js rename to src/components/common/AppBar/AppBarGenericClass.js index 43c5d01..c2d3286 100644 --- a/src/components/common/AppBarGeneric.js +++ b/src/components/common/AppBar/AppBarGenericClass.js @@ -11,18 +11,21 @@ import { getI18nObject } from "@/helpers/frontend/general"; import { AiOutlineSetting, AiOutlineUser } from "react-icons/ai"; import {IoSyncCircleOutline} from "react-icons/io5/index"; import { BiLogOut } from "react-icons/bi"; -import { logoutUser } from "@/helpers/frontend/user"; +import { logoutUser, logoutUser_withRedirect } from "@/helpers/frontend/user"; import Link from "next/link"; import { getSyncTimeout } from "@/helpers/frontend/settings"; import { toast } from "react-toastify"; import Dropdown from 'react-bootstrap/Dropdown'; import { getUserNameFromCookie } from "@/helpers/frontend/cookies"; import Image from "next/image"; -class AppBarGeneric extends Component { +import { signOut, useSession } from "next-auth/react"; +import { getNextAuthSessionData, nextAuthEnabled } from "@/helpers/thirdparty/nextAuth"; + +class AppBarGeneric_ClassComponent extends Component { constructor(props) { super(props) - this.state = { isSyncing: this.props.isSyncing, username: "" } + this.state = { isSyncing: this.props.isSyncing, username: "", } this.i18next = getI18nObject() this.logoClicked = this.logoClicked.bind(this) this.taskViewClicked = this.taskViewClicked.bind(this) @@ -40,10 +43,31 @@ componentDidMount(){ setInterval(() => { //context.syncButtonClicked() //toast.info("syncing") - console.log("getSyncTimeout", getSyncTimeout()) }, getSyncTimeout()) - this.setState({username: getUserNameFromCookie()}) + let username="" + try{ + if(nextAuthEnabled()){ + if(this.props.session) + { + + const { data: session, status } = this.props.session + if(status!="loading"){ + username = session.user.name + + }else{ + + } + } + }else{ + + username = getUserNameFromCookie() + } + + }catch(e){ + + } + this.setState({username: username}) } @@ -79,8 +103,7 @@ async syncButtonClicked() { } logOutClicked() { - logoutUser() - this.props.router.push("/login") + logoutUser_withRedirect(this.props.router) } settingsClicked() { @@ -89,7 +112,6 @@ async syncButtonClicked() { manageFilterClicked() { this.props.router.push("/filters/manage") - } labelManageClicked(){ this.props.router.push("/labels/manage") @@ -185,4 +207,4 @@ async syncButtonClicked() { } } -export default withRouter(AppBarGeneric) \ No newline at end of file +export default withRouter(AppBarGeneric_ClassComponent) \ No newline at end of file diff --git a/src/components/common/AppBar/index.tsx b/src/components/common/AppBar/index.tsx new file mode 100644 index 0000000..54d301e --- /dev/null +++ b/src/components/common/AppBar/index.tsx @@ -0,0 +1,16 @@ +import { useSession } from "next-auth/react"; +import AppBarGeneric_ClassComponent from "./AppBarGenericClass"; +import { useRouter } from "next/router"; + +interface propsType{ + isSyncing?: boolean, + onSynComplete?: Function +} +const AppBarGeneric= ({isSyncing, onSynComplete}:propsType) =>{ + + const session = useSession() + const router = useRouter() + return +} + +export default AppBarGeneric \ No newline at end of file diff --git a/src/components/common/AppBarGeneric copy.js b/src/components/common/AppBarGeneric copy.js deleted file mode 100644 index af5364f..0000000 --- a/src/components/common/AppBarGeneric copy.js +++ /dev/null @@ -1,89 +0,0 @@ -import { PRIMARY_COLOUR } from "@/config/style" -import Row from 'react-bootstrap/Row'; -import Col from "react-bootstrap/Col"; -import { useRouter, withRouter } from "next/router"; -import { Button, Spinner } from "react-bootstrap"; -import React, { Component, useState } from 'react'; -import { fetchLatestEvents, makeSyncRequest } from "@/helpers/frontend/sync"; -import Navbar from 'react-bootstrap/Navbar'; -import Nav from 'react-bootstrap/Nav'; -class AppBarGeneric extends Component { - - constructor(props) { - super(props) - this.state = { isSyncing: this.props.isSyncing } - this.logoClicked = this.logoClicked.bind(this) - this.taskViewClicked = this.taskViewClicked.bind(this) - this.syncButtonClicked = this.syncButtonClicked.bind(this) - - } -componentDidMount(){ - this.setState({isSyncing: this.props.isSyncing}) -} - - -componentDidUpdate(prevProps, prevState) { - - if (this.props.isSyncing !== prevProps.isSyncing) { - - this.setState({isSyncing: this.props.isSyncing}) - } - - -} - - -async syncButtonClicked() { - this.setState({isSyncing: true}) - - //Make a refresh Request for all caldav accounts. - await fetchLatestEvents() - this.setState({isSyncing: false}) - if(this.props.onSynComplete!=null) - { - this.props.onSynComplete() - } - - } - logoClicked() { - this.props.router.push("/") - } - taskViewClicked() { - this.props.router.push('/tasks/list') - } - render() { - var syncButton = this.state.isSyncing ? () : () - return ( - - - - - - - - ) - } -} - -export default withRouter(AppBarGeneric) \ No newline at end of file diff --git a/src/components/common/GenericLists.js b/src/components/common/GenericLists.js index c525c65..f6bbb08 100644 --- a/src/components/common/GenericLists.js +++ b/src/components/common/GenericLists.js @@ -97,19 +97,21 @@ class GenericLists extends Component{ }else{ var message= getMessageFromAPIResponse(body) + console.error("generateLabelList", message, body) + if(message!=null) { if(message=="PLEASE_LOGIN") { // Login required - var redirectURL="/login" - if(window!=undefined) - { + // var redirectURL="/login" + // if(window!=undefined) + // { - redirectURL +="?redirect="+window.location.pathname - } - this.props.router.push(redirectURL) + // redirectURL +="?redirect="+window.location.pathname + // } + // this.props.router.push(redirectURL) } diff --git a/src/components/common/calendars/ShowCalendarList.js b/src/components/common/calendars/ShowCalendarList.js index f89a055..aa07f2f 100644 --- a/src/components/common/calendars/ShowCalendarList.js +++ b/src/components/common/calendars/ShowCalendarList.js @@ -97,25 +97,34 @@ class ShowCalendarList extends Component{ toast.error(this.i18.t("ERROR_GENERIC")) }else{ var message= getMessageFromAPIResponse(caldav_accounts) + console.error("getCaldavAccountsfromDB", message, caldav_accounts) + if(message!=null) { - if(message=="PLEASE_LOGIN") + + if(message!=="PLEASE_LOGIN") { - // Login required - var redirectURL="/login" - if(window!=undefined) - { + toast.error(this.i18.t(message)) + } + // if(message=="PLEASE_LOGIN") + // { + + // // Login required + // var redirectURL="/login" + // if(window!=undefined) + // { - redirectURL +="?redirect="+window.location.pathname - } - this.props.router.push(redirectURL) + // redirectURL +="?redirect="+window.location.pathname + // } + // this.props.router.push(redirectURL) - }else{ - toast.error(this.i18.t(message)) - } + // }else{ + // toast.error(this.i18.t(message)) + + // } } else { diff --git a/src/components/common/calendars/caldavAccounts/CaldavAccounts.js b/src/components/common/calendars/caldavAccounts/CaldavAccounts.js index 0138328..a9dcd7d 100644 --- a/src/components/common/calendars/caldavAccounts/CaldavAccounts.js +++ b/src/components/common/calendars/caldavAccounts/CaldavAccounts.js @@ -28,7 +28,6 @@ export default class CaldavAccounts extends Component{ this.getCaldavAccountsfromDB = this.getCaldavAccountsfromDB.bind(this) this.showAddAccountModal = this.showAddAccountModal.bind(this) - this.getCaldavAccountsfromDB() this.onAccountAddSuccess = this.onAccountAddSuccess.bind(this) this.syncButtonClicked = this.syncButtonClicked.bind(this) this.onAddAccountDismissed = this.onAddAccountDismissed.bind(this) @@ -42,6 +41,8 @@ export default class CaldavAccounts extends Component{ } componentDidMount(){ + this.getCaldavAccountsfromDB() + if(window!=undefined){ const queryString = window.location.search; const params = new URLSearchParams(queryString); diff --git a/src/components/filters/AddFilter.js b/src/components/filters/AddFilter.js index 9be009e..f2a2db3 100644 --- a/src/components/filters/AddFilter.js +++ b/src/components/filters/AddFilter.js @@ -1,4 +1,3 @@ -import AppBarGeneric from "@/components/common/AppBarGeneric" import { SECONDARY_COLOUR } from "@/config/style" import Head from "next/head" import { withRouter } from "next/router" diff --git a/src/components/filters/FilterList.js b/src/components/filters/FilterList.js index 8402a96..169f61a 100644 --- a/src/components/filters/FilterList.js +++ b/src/components/filters/FilterList.js @@ -38,25 +38,33 @@ class FilterList extends Component { toast.error(this.i18next.t("ERROR_GENERIC")) }else{ var message= getMessageFromAPIResponse(filtersFromServer) + console.error("generateList", message, filtersFromServer) + if(message!=null) { - if(message=="PLEASE_LOGIN") + if(message!="PLEASE_LOGIN") { - // Login required - var redirectURL="/login" - if(window!=undefined) - { + // toast.error(this.i18next.t(message)) + } - redirectURL +="?redirect="+window.location.pathname - } - this.props.router.push(redirectURL) + // if(message=="PLEASE_LOGIN") + // { + // // Login required + // var redirectURL="/login" + // if(window!=undefined) + // { - }else{ - toast.error(this.i18next.t(message)) + // redirectURL +="?redirect="+window.location.pathname + // } + // this.props.router.push(redirectURL) - } + + // }else{ + // toast.error(this.i18next.t(message)) + + // } } else { diff --git a/src/components/fullcalendar/DashboardView.js b/src/components/fullcalendar/DashboardView.js index 2f6cb99..db2ab70 100644 --- a/src/components/fullcalendar/DashboardView.js +++ b/src/components/fullcalendar/DashboardView.js @@ -80,25 +80,31 @@ class DashboardView extends Component { }else{ var message =getMessageFromAPIResponse(caldav_accounts) + console.error("getCaldavAccountsfromDB", message, caldav_accounts) + if(message!=null) { - if(message=="PLEASE_LOGIN") + if(message!=="PLEASE_LOGIN") { - // Login required - var redirectURL="/login" - if(window!=undefined) - { + toast.error(this.i18next.t(message)) + } + // if(message=="PLEASE_LOGIN") + // { + // // Login required + // var redirectURL="/login" + // if(window!=undefined) + // { - redirectURL +="?redirect="+window.location.pathname - } - this.props.router.push(redirectURL) + // redirectURL +="?redirect="+window.location.pathname + // } + // this.props.router.push(redirectURL) - }else{ - toast.error(this.i18next.t(message)) + // }else{ + // toast.error(this.i18next.t(message)) - } + // } } else { @@ -198,7 +204,7 @@ class DashboardView extends Component { } //Calculate delta in ms var eventData = this.state.allEvents[newID] - if (this.state.allEvents[newID].type != "VTODO" && this.state.allEvents[newID].type != "VTIMEZONE" && varNotEmpty(this.state.allEvents[newID])) { + if (this.state.allEvents && this.state.allEvents[newID] && this.state.allEvents[newID].type != "VTODO" && this.state.allEvents[newID].type != "VTIMEZONE" && varNotEmpty(this.state.allEvents[newID])) { var delta = e.delta.milliseconds + (e.delta.days * 86400 * 1000) + (e.delta.months * 30 * 86400 * 1000) + (e.delta.years * 365 * 86400 * 1000) //console.log("delta", delta) @@ -248,7 +254,7 @@ class DashboardView extends Component { } async eventResize(e) { - //console.log("eventResize", e) + console.log("eventResize", this.state.allEvents[e.event.id]) var newID = e.event.id if (varNotEmpty(this.state.allEvents[e.event.id]) == false) { //Probably a recurring event. Get ID from map. @@ -256,8 +262,8 @@ class DashboardView extends Component { } //Calculate delta in ms - var eventData = this.state.allEvents[newID] - if (this.state.allEvents[newID].type != "VTODO" && this.state.allEvents[newID].type != "VTIMEZONE" && varNotEmpty(this.state.allEvents[newID])) { + var eventData = _.cloneDeep(this.state.allEvents[newID]) + if (this.state.allEvents && this.state.allEvents[newID] && this.state.allEvents[newID].type != "VTODO" && this.state.allEvents[newID].type != "VTIMEZONE" && varNotEmpty(this.state.allEvents[newID])) { var delta = e.endDelta.milliseconds + (e.endDelta.days * 86400 * 1000) + (e.endDelta.months * 30 * 86400 * 1000) + (e.endDelta.years * 365 * 86400 * 1000) //console.log("delta", delta) @@ -294,6 +300,8 @@ class DashboardView extends Component { toast.error((this.i18next.t("ERROR_GENERIC"))) } + }else{ + console.log("oaspdaosdpoaspdoaspdoasd") } @@ -325,7 +333,6 @@ class DashboardView extends Component { async addEventsToCalendar(allEvents){ var finalEvents = [] - if (isValidResultArray(allEvents.data.message)) { for (let i = 0; i < allEvents.data.message.length; i++) { @@ -459,7 +466,13 @@ class DashboardView extends Component { } */ - //this.state.allEvents[data.uid] = { data: data, event: allEvents.data.message[i].events[j] } + this.setState((prevState, props) => { + var newAllEvents = _.cloneDeep(prevState.allEvents) + newAllEvents[data.uid] = { data: data, event: allEvents.data.message[i].events[j] } + return({allEvents: newAllEvents}) + + }) + // this.state.allEvents[data.uid] = { data: data, event: allEvents.data.message[i].events[j] } } else if (event.type == "VTODO" && this.state.showTasksChecked==true) { @@ -527,7 +540,13 @@ class DashboardView extends Component { } } - + this.setState((prevState, props) => { + var newAllEvents = _.cloneDeep(prevState.allEvents) + newAllEvents[data.uid] = { data: data, event: allEvents.data.message[i].events[j] } + return({allEvents: newAllEvents}) + + }) + } } } diff --git a/src/pages/calendar/view.js b/src/components/page/CalendarViewPage/CalendarView.js similarity index 93% rename from src/pages/calendar/view.js rename to src/components/page/CalendarViewPage/CalendarView.js index b754132..c50dcb8 100644 --- a/src/pages/calendar/view.js +++ b/src/components/page/CalendarViewPage/CalendarView.js @@ -1,8 +1,9 @@ -import AppBarGeneric from "@/components/common/AppBarGeneric"; +import AppBarGeneric from "@/components/common/AppBar"; import DashboardView from "@/components/fullcalendar/DashboardView"; import { getI18nObject } from "@/helpers/frontend/general"; +import { useSession } from "next-auth/react"; import Head from "next/head"; -import { withRouter } from "next/router"; +import { useRouter, withRouter } from "next/router"; import { Component } from "react"; import "react-datetime/css/react-datetime.css"; diff --git a/src/components/page/CombinedView.js b/src/components/page/CombinedView.js index 1042f30..4ab2b25 100644 --- a/src/components/page/CombinedView.js +++ b/src/components/page/CombinedView.js @@ -1,6 +1,3 @@ -import Head from 'next/head' -import TaskList from '@/components/tasks/TaskList' -import AppBarGeneric from '@/components/common/AppBarGeneric' import { Col, Row } from 'react-bootstrap' import { getTodaysDateUnixTimeStamp, varNotEmpty } from '@/helpers/general' import DashboardView from '@/components/fullcalendar/DashboardView' @@ -88,6 +85,7 @@ export default class CombinedView extends Component { render(){ var borderLeft = this.state.showListColumn ? '3px solid ' + SECONDARY_COLOUR : "" var leftColumnMatter = ( <> + {/* diff --git a/src/pages/filters/manage.js b/src/components/page/ManageFiltersPage/ManageFilters.js similarity index 87% rename from src/pages/filters/manage.js rename to src/components/page/ManageFiltersPage/ManageFilters.js index 4fd8fb9..3d8b971 100644 --- a/src/pages/filters/manage.js +++ b/src/components/page/ManageFiltersPage/ManageFilters.js @@ -1,4 +1,4 @@ -import AppBarGeneric from "@/components/common/AppBarGeneric" +import AppBarGeneric from "@/components/common/AppBar" import { Loading } from "@/components/common/Loading" import AddFilter from "@/components/filters/AddFilter" import { Toastify } from "@/components/Generic" @@ -8,8 +8,9 @@ import { filtertoWords, getFiltersFromServer } from "@/helpers/frontend/filters" import { getI18nObject } from "@/helpers/frontend/general" import { getMessageFromAPIResponse } from "@/helpers/frontend/response" import { dateTimeReviver } from "@/helpers/general" +import { useSession } from "next-auth/react" import Head from "next/head" -import { withRouter } from "next/router" +import { useRouter, withRouter } from "next/router" import { Component } from "react" import { Col, Row } from "react-bootstrap" import Button from "react-bootstrap/Button" @@ -71,25 +72,32 @@ class ManageFilters extends Component{ toast.error(this.i18next.t("ERROR_GENERIC")) }else{ var message= getMessageFromAPIResponse(filtersFromServer) + console.error("getAllTodosFromServer", message, filtersFromServer) + if(message!=null) { - if(message=="PLEASE_LOGIN") + if(message!=="PLEASE_LOGIN") { - // Login required - var redirectURL="/login" - if(window!=undefined) - { + toast.error(this.i18next.t(message)) + } + // if(message=="PLEASE_LOGIN") + // { + // // Login required + // var redirectURL="/login" + // if(window!=undefined) + // { - redirectURL +="?redirect="+window.location.pathname - } - this.props.router.push(redirectURL) + // redirectURL +="?redirect="+window.location.pathname + // } + // this.props.router.push(redirectURL) - }else{ - toast.error(this.i18next.t(message)) - } + // }else{ + // toast.error(this.i18next.t(message)) + + // } } else { @@ -168,7 +176,7 @@ class ManageFilters extends Component{ - +

{this.i18next.t("MANAGE_FILTERS")}

{this.i18next.t("MANAGE_FILTERS_DESC")}

@@ -185,5 +193,6 @@ class ManageFilters extends Component{ } } + export default withRouter(ManageFilters) diff --git a/src/pages/labels/manage.js b/src/components/page/MangerLabelsPage/ManageLabels.js similarity index 84% rename from src/pages/labels/manage.js rename to src/components/page/MangerLabelsPage/ManageLabels.js index 0599afc..b872bcb 100644 --- a/src/pages/labels/manage.js +++ b/src/components/page/MangerLabelsPage/ManageLabels.js @@ -1,13 +1,14 @@ import Head from 'next/head' import Container from 'react-bootstrap/Container'; -import AppBarGeneric from "@/components/common/AppBarGeneric" +import AppBarGeneric from "@/components/common/AppBar" import CaldavAccounts from '@/components/common/calendars/caldavAccounts/CaldavAccounts' import LabelManager from '@/components/LabelManager'; import { makeUpdateLabelRequest } from '@/helpers/frontend/labels'; import { getAuthenticationHeadersforUser } from '@/helpers/frontend/user'; import { getI18nObject } from '@/helpers/frontend/general'; +import { withRouter } from 'next/router'; -export default function ManageLables({reply}) { +function ManageLabels() { var i18next = getI18nObject() return ( @@ -28,3 +29,5 @@ export default function ManageLables({reply}) { ) } +export default withRouter(ManageLabels) + diff --git a/src/pages/accounts/settings.js b/src/components/page/SettingsPage/SettingsPage.js similarity index 95% rename from src/pages/accounts/settings.js rename to src/components/page/SettingsPage/SettingsPage.js index f60515f..59d2e85 100644 --- a/src/pages/accounts/settings.js +++ b/src/components/page/SettingsPage/SettingsPage.js @@ -1,13 +1,11 @@ -import AppBarGeneric from "@/components/common/AppBarGeneric"; +import AppBarGeneric from "@/components/common/AppBar"; import { Loading } from "@/components/common/Loading"; import { displayErrorMessageFromAPIResponse, getI18nObject } from "@/helpers/frontend/general"; import Head from "next/head"; -import { Col, Container, ProgressBar, Row } from "react-bootstrap"; -import Placeholder from 'react-bootstrap/Placeholder'; +import { Col, Container, Row } from "react-bootstrap"; const { withRouter } = require("next/router"); const { Component } = require("react"); -import Card from 'react-bootstrap/Card'; -import { getAuthenticationHeadersforUser } from "@/helpers/frontend/user"; +import { getAuthenticationHeadersforUser, logoutUser, logoutUser_withRedirect } from "@/helpers/frontend/user"; import { getAPIURL, isValidResultArray, logVar, varNotEmpty } from "@/helpers/general"; import { BACKGROUND_GRAY } from "@/config/style"; import moment from "moment"; @@ -19,7 +17,8 @@ import Button from "react-bootstrap/Button"; import DefaultCalendarViewSelect from "@/components/accounts/DefaultCalendarViewSelect"; import { VERSION_NUMBER } from "@/config/constants"; import { setDefaultCalendarID } from "@/helpers/frontend/cookies"; -class Settings extends Component { +import { getMessageFromAPIResponse } from "@/helpers/frontend/response"; +class SettingsPage extends Component { constructor(props) { super(props) @@ -84,8 +83,11 @@ class Settings extends Component { } }else{ - console.log(body) - toast.error(this.state.i18next.t("ERROR_GETTING_SETTINGS")) + var message = getMessageFromAPIResponse(body) + console.error("getAllUserSettings", message, body) + // if(message==="PLEASE_LOGIN"){ + // logoutUser_withRedirect(this.props.router) + // } } }).catch(e =>{ @@ -166,7 +168,7 @@ class Settings extends Component { } } else { - toast.error(this.i18next.t("ERROR_GENERIC")) + console.error(this.i18next.t("ERROR_GENERIC"), body) } @@ -394,4 +396,4 @@ class Settings extends Component { } -export default withRouter(Settings) +export default withRouter(SettingsPage) diff --git a/src/pages/tasks/list.js b/src/components/page/TaskViewPage/TaskViewList.js similarity index 99% rename from src/pages/tasks/list.js rename to src/components/page/TaskViewPage/TaskViewList.js index e79abb8..c04dad0 100644 --- a/src/pages/tasks/list.js +++ b/src/components/page/TaskViewPage/TaskViewList.js @@ -1,6 +1,6 @@ import Head from 'next/head' import TaskList from '@/components/tasks/TaskList' -import AppBarGeneric from '@/components/common/AppBarGeneric' +import AppBarGeneric from '@/components/common/AppBar' import '@/../bootstrap/dist/css/bootstrap.min.css' import GenericLists from '@/components/common/GenericLists' import { Component } from 'react' diff --git a/src/components/tasks/TaskList.js b/src/components/tasks/TaskList.js index 8d6c00a..9317a1b 100644 --- a/src/components/tasks/TaskList.js +++ b/src/components/tasks/TaskList.js @@ -109,29 +109,37 @@ import { getAPIURL, logVar } from '@/helpers/general'; toast.error(this.i18next.t("ERROR_GENERIC")) }else{ var message= getMessageFromAPIResponse(responseFromServer) + console.error("getCaldavAccountsfromDB", message, responseFromServer) + if(message!=null) { - if(message=="PLEASE_LOGIN") + if(message!="PLEASE_LOGIN") { - // Login required - var redirectURL="/login" - if(window!=undefined) - { + toast.error(this.i18next.t(message)) + } - redirectURL +="?redirect="+window.location.pathname - } - if(this.props.router!=undefined) - { - this.props.router.push(redirectURL) + // if(message=="PLEASE_LOGIN") + // { + // // Login required + // var redirectURL="/login" + // if(window!=undefined) + // { - } + // redirectURL +="?redirect="+window.location.pathname + // } + // if(this.props.router!=undefined) + // { + // this.props.router.push(redirectURL) - }else{ - toast.error(this.i18next.t(message)) + // } - } + + // }else{ + // toast.error(this.i18next.t(message)) + + // } } else { @@ -232,25 +240,33 @@ import { getAPIURL, logVar } from '@/helpers/general'; } else { var message= getMessageFromAPIResponse(response) + console.error("refreshCalendars", message, response) + if(message!=null) { - if(message=="PLEASE_LOGIN") + + if(message!="PLEASE_LOGIN") { - // Login required - var redirectURL="/login" - if(window!=undefined) - { + toast.error(this.i18next.t(message)) + } - redirectURL +="?redirect="+window.location.pathname - } - this.props.router.push(redirectURL) + // if(message=="PLEASE_LOGIN") + // { + // // Login required + // var redirectURL="/login" + // if(window!=undefined) + // { - }else{ - toast.error(this.i18next.t(message)) + // redirectURL +="?redirect="+window.location.pathname + // } + // this.props.router.push(redirectURL) - } + + // }else{ + + // } } else { diff --git a/src/components/tasks/TaskUI.js b/src/components/tasks/TaskUI.js index 1ea6706..52d339e 100644 --- a/src/components/tasks/TaskUI.js +++ b/src/components/tasks/TaskUI.js @@ -302,14 +302,15 @@ export default class TaskUI extends Component { } onTaskSubmittoServer(body) { this.setState({ showTaskEditModal: false, showTaskEditor: false }) + var message= getMessageFromAPIResponse(body) if (body != null) { if (body.success == true) { - toast.success(this.i18next.t(body.data.message)) + toast.success(this.i18next.t(message)) this.props.fetchEvents(body.data.refresh) } else { - toast.error(this.i18next.t(body.data.message)) + toast.error(message) } } @@ -321,7 +322,6 @@ export default class TaskUI extends Component { onSubtaskSubmittoServer(body) { this.setState({ showSubtaskEditor: false }) - if (body != null) { if (body.success == true) { toast.success(this.i18next.t("EVENT_SUBMIT_OK")) @@ -330,12 +330,12 @@ export default class TaskUI extends Component { } else { - toast.error(this.i18next.t(body.data.message)) + toast.error(this.i18next.t(message)) } } else { - toast.error(body) + toast.error(this.i18next.t("ERROR_GENERIC")) } } diff --git a/src/config/constants.js b/src/config/constants.js index b336e36..d3da4e6 100644 --- a/src/config/constants.js +++ b/src/config/constants.js @@ -1,4 +1,4 @@ -export const VERSION_NUMBER = "0.2.0" +export const VERSION_NUMBER = "0.3.0" /* * SYSTEM_DEFAULT_LABEL_PREFIX: Default prefix applied to all system generated labels like * "My Day" diff --git a/src/helpers/api/installSequelize.ts b/src/helpers/api/installSequelize.ts new file mode 100644 index 0000000..d648ffe --- /dev/null +++ b/src/helpers/api/installSequelize.ts @@ -0,0 +1,14 @@ +import { caldav_accounts } from "models/caldav_accounts" +import { calendar_events } from "models/calendar_events" +import { calendars } from "models/calendars" +import { custom_filters } from "models/custom_filters" +import { labels } from "models/labels" +import { otp_table } from "models/otp_table" +import {settings} from 'models/settings' +import { ssid_table } from "models/ssid_table" +import { users } from "models/users" + + +export async function isInstalledV2(){ + +} \ No newline at end of file diff --git a/src/helpers/api/user.js b/src/helpers/api/user.js index 366261c..bbbd555 100644 --- a/src/helpers/api/user.js +++ b/src/helpers/api/user.js @@ -1,10 +1,15 @@ -import { getConnectionVar } from '@/helpers/api/db'; +import { getConnectionVar, getSequelizeObj } from '@/helpers/api/db'; import crypto from "crypto" import { Base64 } from 'js-base64'; import { getRegistrationStatus, userRegistrationAllowed } from './settings'; import { varNotEmpty } from '../general'; import bcrypt from 'bcryptjs'; - +import { getUserIDFromNextAuthSession, nextAuthEnabled } from '../thirdparty/nextAuth'; +import { getServerSession } from 'next-auth'; +import { authOptions } from '@/pages/api/auth/[...nextauth]'; +import { getToken } from 'next-auth/jwt'; +import { getRandomString } from '../crypto'; +import { users } from 'models/users'; export async function getUserDetailsfromUsername(username) { var con = getConnectionVar() @@ -96,10 +101,10 @@ export async function forceInsertUserIntoDB(username,password,email,level) //var password = crypto.createHash('sha512').update(password).digest('hex') const salt = await bcrypt.genSalt(10) const passwordHash = await bcrypt.hash(password, salt) - + const id = getRandomString(16) var created=Math.floor(Date.now() / 1000) - con.query('INSERT INTO users (username, password, email, created, userhash,level) VALUES (?,?, ? ,?,?,?)', [username, passwordHash, email, created, userhash,level], function (error, results, fields) { + con.query('INSERT INTO users (username, password, email, created, userhash,level,id) VALUES (?,?, ? ,?,?,?,?)', [username, passwordHash, email, created, userhash,level, id], function (error, results, fields) { if (error) { console.log(error.message) } @@ -244,6 +249,40 @@ export async function getAllSSIDFromDB(userhash) } +export async function getUserIDFromLogin(req,res){ + if(!varNotEmpty(req) || !varNotEmpty(res)){ + return null + } + + if(nextAuthEnabled()){ + const session = await getServerSession(req, res, authOptions) + const id_fromNextAuth= getUserIDFromNextAuthSession(session) + return await getUserIDFromNextAuthID(id_fromNextAuth) + }else{ + var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + const userid = await getUseridFromUserhash(userHash[0]) + return userid + } + +} + +export async function getUserIDFromNextAuthID(id){ + + const Users= users.initModel(getSequelizeObj()) + const res = await Users.findOne({ + where:{ + id:id + }, + raw: true, + nest: true, + }) + + if(res && res.users_id){ + return res.users_id + } + return null +} + export async function getUserHashSSIDfromAuthorisation(authHeaders) { if(authHeaders!=null && authHeaders!="" && authHeaders!=undefined && authHeaders!="null") @@ -259,37 +298,46 @@ export async function getUserHashSSIDfromAuthorisation(authHeaders) } } -export async function middleWareForAuthorisation(authHeaders) +export async function middleWareForAuthorisation(req, res) { - try{ - if(authHeaders!=null && authHeaders!="" && authHeaders!=undefined &&authHeaders!="null") - { - - var userssidArray= await getUserHashSSIDfromAuthorisation(authHeaders) - if(userssidArray!=null && Array.isArray(userssidArray) && userssidArray.length==2) - { - - const isValid= await checkSSIDValidity(userssidArray[0], userssidArray[1]) - //console.log(isValid) - return isValid - - - } - else - { + if(!varNotEmpty(req)){ + return false + } + if(nextAuthEnabled()){ + const session = await getServerSession(req, res, authOptions) + if(session){ + return true + }else{ return false } - // - } - else - { - return false } - } - catch(e) - { - //console.log("middleWareForAuthorisation", e) - return false + else{ + try{ + const authHeaders = req.headers.authorization + + var userssidArray= await getUserHashSSIDfromAuthorisation(authHeaders) + if(userssidArray!=null && Array.isArray(userssidArray) && userssidArray.length==2) + { + + const isValid= await checkSSIDValidity(userssidArray[0], userssidArray[1]) + //console.log(isValid) + return isValid + + + } + else + { + return false + } + // + + } + catch(e) + { + //console.log("middleWareForAuthorisation", e) + return false + } + } } diff --git a/src/helpers/frontend/classes/APIRequests.js b/src/helpers/frontend/classes/APIRequests.js index 4eb7d03..6d92552 100644 --- a/src/helpers/frontend/classes/APIRequests.js +++ b/src/helpers/frontend/classes/APIRequests.js @@ -45,25 +45,32 @@ export class APIRequests{ toast.error(this.i18next.t("ERROR_GENERIC")) }else{ var message= getMessageFromAPIResponse(responseFromServer) + console.error("getAllTodosFromServer", message, responseFromServer) + if(message!=null) { - if(message=="PLEASE_LOGIN") + + if(message!=="PLEASE_LOGIN") { - // Login required - var redirectURL="/login" - if(window!=undefined) - { + toast.error(this.i18next.t(message)) + } + // if(message=="PLEASE_LOGIN") + // { + // // Login required + // var redirectURL="/login" + // if(window!=undefined) + // { - redirectURL +="?redirect="+window.location.pathname - } - this.props.router.push(redirectURL) + // redirectURL +="?redirect="+window.location.pathname + // } + // this.props.router.push(redirectURL) - }else{ - toast.error(this.i18next.t(message)) + // }else{ + // toast.error(this.i18next.t(message)) - } + // } } else { diff --git a/src/helpers/frontend/cookies.js b/src/helpers/frontend/cookies.js index b813c6f..4e134e1 100644 --- a/src/helpers/frontend/cookies.js +++ b/src/helpers/frontend/cookies.js @@ -3,6 +3,19 @@ import { getAuthenticationHeadersforUser } from './user' import { getAPIURL, logVar, varNotEmpty } from '../general' import { getMessageFromAPIResponse } from './response' +export function deleteAllCookies(){ + Cookies.remove("DEFAULT_CALENDAR_ID") + Cookies.remove("MMDL_USERNAME") + Cookies.remove("USER_SETTING_SYNCTIMEOUT") + Cookies.remove("USER_DATA_LABELS") + Cookies.remove("DEFAULT_VIEW_CALENDAR") + Cookies.remove("USERHASH") + Cookies.remove("USER_PREFERENCE_CALENDARS_TO_SHOW") + Cookies.remove("SSID") + + + +} export function setCookie(cname, cvalue, exdays=10000) { diff --git a/src/helpers/frontend/user.js b/src/helpers/frontend/user.js index 44f9052..471ca8c 100644 --- a/src/helpers/frontend/user.js +++ b/src/helpers/frontend/user.js @@ -1,6 +1,11 @@ import Cookies from "js-cookie"; import { getUserDB } from "./db"; import { Base64 } from "js-base64"; +import { nextAuthEnabled } from "../thirdparty/nextAuth"; +import { signOut } from "next-auth/react"; +import { getAPIURL, varNotEmpty } from "../general"; +import axios from "axios"; +import { deleteAllCookies } from "./cookies"; export async function getUserData() { @@ -22,6 +27,32 @@ export function logoutUser() Cookies.remove("SSID") Cookies.remove("USER_DATA_LABELS") Cookies.remove("USER_SETTING_SYNCTIMEOUT") + + deleteAllCookies() + //Logout nextAuth Sessions. + if(nextAuthEnabled()){ + signOut() + } +} + +/** + * Manages user logout with redirect. Calls the Logout function (which signs out the user either with NextAuth.js or with inbuilt mechanism, then redirects appropriately.) + */ +export function logoutUser_withRedirect(router, redirectURL){ + logoutUser() + if(varNotEmpty(router)){ + if(nextAuthEnabled()){ + router.push('/') + }else{ + var url = '/login' + if(varNotEmpty(redirectURL)){ + url+="/?redirect="+redirectURL + } + router.push(url) + + } + } + } export function getUserDataFromCookies() { return ({ @@ -40,4 +71,41 @@ export async function getAuthenticationHeadersforUser() { } export async function insertUserdata() { +} + + +export async function checkLogin_InBuilt(router, redirectURL){ + const url_api=getAPIURL()+"auth/inbuilt/check" + const authorisationData=await getAuthenticationHeadersforUser() + + const requestOptions = + { + method: 'GET', + mode: 'cors', + headers: new Headers({'authorization': authorisationData, 'Content-Type':'application/json'}), + } + + return new Promise( (resolve, reject) => { + fetch(url_api, requestOptions) + .then(response => response.json()) + .then((body) =>{ + if(varNotEmpty(body) && varNotEmpty(body.success)){ + if(body.success!=true){ + logoutUser_withRedirect(router, redirectURL) + } + + }else{ + logoutUser_withRedirect(router, redirectURL) + } + return resolve(true) + }).catch(e=> + { + + console.error("checkLogin_InBuilt", e) + return resolve(false) + + } + ) + + }) } \ No newline at end of file diff --git a/src/helpers/installation.ts b/src/helpers/installation.ts new file mode 100644 index 0000000..c15e8a9 --- /dev/null +++ b/src/helpers/installation.ts @@ -0,0 +1,3 @@ +export function isInstalledV2(){ + +} \ No newline at end of file diff --git a/src/helpers/models.ts b/src/helpers/models.ts new file mode 100644 index 0000000..aa55c00 --- /dev/null +++ b/src/helpers/models.ts @@ -0,0 +1,4 @@ +export function getAllDBModels(){ + + +} \ No newline at end of file diff --git a/src/helpers/thirdparty/keycloak.ts b/src/helpers/thirdparty/keycloak.ts new file mode 100644 index 0000000..f1e75e9 --- /dev/null +++ b/src/helpers/thirdparty/keycloak.ts @@ -0,0 +1,70 @@ +import Keycloak from 'keycloak-js'; +import { varNotEmpty } from '../general'; +import { getI18nObject } from '../frontend/general'; +const i18next = getI18nObject() + +/** + * Checks if the user is logged in. + * If no value of NEXT_PUBLIC_OPEN_ID_PROVIDER is provided as an environment variable + * we will assume that the user wants to use MMDL's inbuilt login functions. + * @returns Promise of a blooean. True if user is logged in. + */ +export async function isUserLoggedIn(): Promise{ + + if(!varNotEmpty(process.env.NEXT_PUBLIC_OPEN_ID_PROVIDER)){ + return true + } + + + try{ + switch (process.env.NEXT_PUBLIC_OPEN_ID_PROVIDER.trim().toUpperCase()){ + + case "KEYCLOAK": + return silentCheckSSO_KeyCloak(); + case "": + return true + default: + throw new Error(i18next.t("ERROR_INVALID_VALUE_OPENID_PROVIDER")) + + } + + }catch(e){ + console.error(e) + throw new Error(i18next.t("ERROR_INVALID_VALUE_OPENID_PROVIDER")) + } + + +} + +/** + * Checks if user is logged in with Keycloak. + * Uses check-sso in Keycloak initiation. + */ +export async function silentCheckSSO_KeyCloak(){ + const keycloak = new Keycloak({ + url: process.env.NEXT_PUBLIC_OPEN_ID_PROVIDER_URL, + realm: process.env.NEXT_PUBLIC_OPEN_ID_PROVIDER_REALM, + clientId: process.env.NEXT_PUBLIC_OPEN_ID_PROVIDER_CLIENT_ID + }); + + + try { + keycloak.init({onLoad: "login-required"}).then((authenticated) =>{ + + if(authenticated){ + return true + }else{ + return false + } + + }) + + } catch (error) { + console.log('Failed to initialize adapter:', error) + } + + return false + + + +} \ No newline at end of file diff --git a/src/helpers/thirdparty/nextAuth.ts b/src/helpers/thirdparty/nextAuth.ts new file mode 100644 index 0000000..277703e --- /dev/null +++ b/src/helpers/thirdparty/nextAuth.ts @@ -0,0 +1,26 @@ + +export function nextAuthEnabled(){ + if(process.env.NEXT_PUBLIC_USE_NEXT_AUTH==="true"){ + return true + }else{ + return false + } +} + +/** + * Takes in result of getServerSession from NextAuth.js + * and return the user id. + */ +export function getUserIDFromNextAuthSession(session: any) +{ + if(session){ + if(session.user) + { + if(session.user.id){ + return session.user.id + } + } + } + + return null +} \ No newline at end of file diff --git a/src/i18n/strings.json b/src/i18n/strings.json index 120e447..a206e58 100644 --- a/src/i18n/strings.json +++ b/src/i18n/strings.json @@ -82,6 +82,7 @@ "EVENT_NEEDS_BOTH_FROM_AND_TO": "Event needs both a 'From' and 'To' date.", "EVENT_SUBMIT_OK": "Event successfully added.", "EVENT_SUMMARY": "Event Summary", + "ERROR_INVALID_VALUE_OPENID_PROVIDER":"Invalid value of NEXT_PUBLIC_OPEN_ID_PROVIDER was provided as environment variable.", "EVERY": "Every", "FILTERS": "Filters", "FILTER_BY_DUE": "Filter by Due", diff --git a/src/pages/_app.js b/src/pages/_app.js index 882965b..77b3014 100644 --- a/src/pages/_app.js +++ b/src/pages/_app.js @@ -3,9 +3,8 @@ import 'bootstrap/dist/css/bootstrap.min.css'; import 'bootstrap-icons/font/bootstrap-icons.css' import { Toastify } from '@/components/Generic'; import 'react-toastify/dist/ReactToastify.css'; -import Script from 'next/script'; import '../styles/global.css' - +import { SessionProvider } from "next-auth/react" function load() { NProgress.start(); @@ -16,10 +15,13 @@ function stop() NProgress.done(); } -export default function App({ Component, pageProps }) { +export default function App({ Component, pageProps: {session, ...pageProps }}) { + return (<> - - - - ) + + + + + + ) } diff --git a/src/pages/accounts/caldav.js b/src/pages/accounts/caldav.js index f6a1ec5..98a9880 100644 --- a/src/pages/accounts/caldav.js +++ b/src/pages/accounts/caldav.js @@ -1,12 +1,32 @@ import Head from 'next/head' import Container from 'react-bootstrap/Container'; -import AppBarGeneric from "@/components/common/AppBarGeneric" +import AppBarGeneric from "@/components/common/AppBar" import CaldavAccounts from '@/components/common/calendars/caldavAccounts/CaldavAccounts' import { getI18n } from 'react-i18next'; import { getI18nObject } from '@/helpers/frontend/general'; +import { signIn, useSession } from 'next-auth/react'; +import { useEffect } from 'react'; +import { nextAuthEnabled } from '@/helpers/thirdparty/nextAuth'; +import { useRouter } from 'next/router'; +import { checkLogin_InBuilt } from '@/helpers/frontend/user'; export default function Caldav() { + const { data: session, status } = useSession() + const router = useRouter() + + useEffect(() =>{ + + if(nextAuthEnabled()){ + if (status=="unauthenticated" ) { + signIn() + } + }else{ + // Check login using inbuilt function. + checkLogin_InBuilt(router,"/accounts/caldav") + } + }, [status, router]) + var i18next = getI18nObject() return ( <> @@ -15,7 +35,7 @@ export default function Caldav() { - +
diff --git a/src/pages/accounts/settings.tsx b/src/pages/accounts/settings.tsx new file mode 100644 index 0000000..11d2918 --- /dev/null +++ b/src/pages/accounts/settings.tsx @@ -0,0 +1,35 @@ +import SettingsPage from "@/components/page/SettingsPage/SettingsPage"; +import { checkLogin_InBuilt, logoutUser_withRedirect } from "@/helpers/frontend/user"; +import { nextAuthEnabled } from "@/helpers/thirdparty/nextAuth"; +import { signIn, useSession } from "next-auth/react"; +import { useRouter } from "next/router"; +import { useEffect } from "react"; + + +export default function Settings(){ + const { data: session, status } = useSession() + const router = useRouter() + + useEffect(() =>{ + + if(nextAuthEnabled()){ + if (status=="unauthenticated" ) { + signIn() + } + }else{ + // Check login using inbuilt function. + + checkLogin_InBuilt(router, '/accounts/settings') + } + }, [status,router]) + + + + + + return( + <> + + + ) +} \ No newline at end of file diff --git a/src/pages/api/admin/deleteuser.js b/src/pages/api/admin/deleteuser.js index 33fd56d..3d2b258 100644 --- a/src/pages/api/admin/deleteuser.js +++ b/src/pages/api/admin/deleteuser.js @@ -1,17 +1,24 @@ import Settings from "@/helpers/api/classes/Settings" import { User } from "@/helpers/api/classes/User" import { getICS } from "@/helpers/api/ical" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { varNotEmpty } from "@/helpers/general" import moment from "moment" export default async function handler(req, res) { if (req.method === 'DELETE') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if( await middleWareForAuthorisation(req, res)) { if(varNotEmpty(req.query.userid)&& req.query.userid!="") { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + + var userObj = new User(userid) var isAdmin= await userObj.isAdmin() diff --git a/src/pages/api/admin/getusers.js b/src/pages/api/admin/getusers.js index 8a5acb1..05d4405 100644 --- a/src/pages/api/admin/getusers.js +++ b/src/pages/api/admin/getusers.js @@ -1,16 +1,22 @@ import Settings from "@/helpers/api/classes/Settings" import { User } from "@/helpers/api/classes/User" import { getICS } from "@/helpers/api/ical" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { varNotEmpty } from "@/helpers/general" import moment from "moment" export default async function getusers_handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var userObj = new User(userid) var isAdmin= await userObj.isAdmin() diff --git a/src/pages/api/auth/[...nextauth].js b/src/pages/api/auth/[...nextauth].js new file mode 100644 index 0000000..2f3a3e7 --- /dev/null +++ b/src/pages/api/auth/[...nextauth].js @@ -0,0 +1,22 @@ +import authProviders from "config/nextAuthProviders" +import NextAuth from "next-auth" +import SequelizeAdapter from "@auth/sequelize-adapter"; +import { Sequelize } from "sequelize"; +import { getSequelizeObj } from "@/helpers/api/db"; + +const sequelize = getSequelizeObj() + +export const authOptions = { + // Configure one or more authentication providers + providers:authProviders, + adapter: SequelizeAdapter(sequelize,{ + synchronize: false + }), + callbacks: { + session: async (session, user) => { + return Promise.resolve(session) + } + } +} + +export default NextAuth(authOptions) \ No newline at end of file diff --git a/src/pages/api/auth/inbuilt/check.js b/src/pages/api/auth/inbuilt/check.js new file mode 100644 index 0000000..e4c5011 --- /dev/null +++ b/src/pages/api/auth/inbuilt/check.js @@ -0,0 +1,15 @@ +import { middleWareForAuthorisation } from "@/helpers/api/user"; + +export default async function checkLoginHandler(req, res) { + if (req.method === 'GET') { + if(await middleWareForAuthorisation(req, res)) + { + res.status(200).json({ success: true, data: { message: 'LOGIN_OK'} }) + + }else{ + res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + + } +} \ No newline at end of file diff --git a/src/pages/api/caldav/calendars/add/event.js b/src/pages/api/caldav/calendars/add/event.js index b6d9654..30492a4 100644 --- a/src/pages/api/caldav/calendars/add/event.js +++ b/src/pages/api/caldav/calendars/add/event.js @@ -2,20 +2,25 @@ import { createEventinCalDAVAccount } from '@/helpers/api/cal/caldav'; import { checkifUserHasAccesstoRequestedCalendar, getCaldavAccountfromUserID, getCaldavAccountIDFromCalendarID, getCalendarfromCalendarID } from '@/helpers/api/cal/calendars'; import { getAllLablesFromDB } from '@/helpers/api/cal/labels'; import { getObjectFromDB, insertObjectIntoDB, updateObjectinDB } from '@/helpers/api/cal/object'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; import { getRandomString } from '@/helpers/crypto'; import { logVar } from '@/helpers/general'; export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { //console.log(req.body) if(req.body.etag!=null && req.body.etag.trim()!="" && req.body.data!=null && req.body.data.trim()!="" && req.body.updated!=null && req.body.updated.toString().trim()!="" && req.body.type!=null && req.body.type.trim()!="" && req.body.calendar_id!=null && req.body.calendar_id.toString().trim()!="") { logVar(req.body.data, '/api/caldav/calendars/add/event') - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) - var userid = await getUseridFromUserhash(userHash[0]) + // var userid = await getUseridFromUserhash(userHash[0]) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } //First we check if user has access to calendar. var currentCaldavAccountID=await getCaldavAccountIDFromCalendarID(req.body.calendar_id) diff --git a/src/pages/api/caldav/calendars/events/all.js b/src/pages/api/caldav/calendars/events/all.js index ff637bf..c325706 100644 --- a/src/pages/api/caldav/calendars/events/all.js +++ b/src/pages/api/caldav/calendars/events/all.js @@ -3,19 +3,26 @@ import { getCaldavAccountsfromUserid, getCalendarsfromCaldavAccountsID } from '@ import { updateLabels } from '@/helpers/api/cal/labels'; import { User } from '@/helpers/api/classes/User'; import { process_calendarQueryResults } from '@/helpers/api/tsdav'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; import { logVar } from '@/helpers/general'; const LOGTAG= "Source: /api/caldav/calendars/events/all" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { logVar(req.query, LOGTAG) if(req.query.caldav_accounts_id!=null) { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) - var userid = await getUseridFromUserhash(userHash[0]) + // var userid = await getUseridFromUserhash(userHash[0]) + + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var userObj = new User(userid) //console.log("hasAccesstoCaldavAccountID", ) if(await userObj.hasAccesstoCaldavAccountID(req.query.caldav_accounts_id)) diff --git a/src/pages/api/caldav/calendars/events/db/all.js b/src/pages/api/caldav/calendars/events/db/all.js index ce3d594..3b103ee 100644 --- a/src/pages/api/caldav/calendars/events/db/all.js +++ b/src/pages/api/caldav/calendars/events/db/all.js @@ -1,16 +1,23 @@ import { checkifUserHasAccesstoRequestedCalendar, getCaldavAccountsfromUserid, getCalendarsfromCaldavAccountsID } from "@/helpers/api/cal/calendars" import { getCalendarObjectsFromCalendar, getCalendarObjectsFromCalendarbyType } from "@/helpers/api/cal/object" -import { getUserHashSSIDfromAuthorisation, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserHashSSIDfromAuthorisation, getUserIDFromLogin, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + + // var userid = await getUseridFromUserhash(userHash[0]) + + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } - var userid = await getUseridFromUserhash(userHash[0]) var allCalendarEvents =[] var caldav_accounts = await getCaldavAccountsfromUserid(userid) if(caldav_accounts!=null && Array.isArray(caldav_accounts) && caldav_accounts.length>0) diff --git a/src/pages/api/caldav/calendars/events/db/index.js b/src/pages/api/caldav/calendars/events/db/index.js index 74cf5b8..aef97ea 100644 --- a/src/pages/api/caldav/calendars/events/db/index.js +++ b/src/pages/api/caldav/calendars/events/db/index.js @@ -1,17 +1,24 @@ import { checkifUserHasAccesstoRequestedCalendar, getCaldavAccountsfromUserid } from "@/helpers/api/cal/calendars" import { getCalendarObjectsFromCalendar, getCalendarObjectsFromCalendarbyType } from "@/helpers/api/cal/object" -import { getUserHashSSIDfromAuthorisation, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserHashSSIDfromAuthorisation, getUserIDFromLogin, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.query.caldav_accounts_id!=null && req.query.calendars_id!=null) { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + + // var userid = await getUseridFromUserhash(userHash[0]) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + - var userid = await getUseridFromUserhash(userHash[0]) var allCalendarEvents =null var calendar=await checkifUserHasAccesstoRequestedCalendar(userid, req.query.caldav_accounts_id, req.query.calendars_id) diff --git a/src/pages/api/caldav/calendars/events/fetchevents.js b/src/pages/api/caldav/calendars/events/fetchevents.js index db4e767..97a49a2 100644 --- a/src/pages/api/caldav/calendars/events/fetchevents.js +++ b/src/pages/api/caldav/calendars/events/fetchevents.js @@ -1,18 +1,24 @@ import { checkifUserHasAccesstoRequestedCalendar } from '@/helpers/api/cal/calendars'; -import { checkSSIDValidity, getUserHashSSIDfromAuthorisation, getUseridFromUserhash, middleWareForAuthorisation } from '@/helpers/api/user'; +import { checkSSIDValidity, getUserHashSSIDfromAuthorisation, getUserIDFromLogin, getUseridFromUserhash, middleWareForAuthorisation } from '@/helpers/api/user'; import { getCaldavClient, saveCalendarEventsintoDB } from '@/helpers/api/cal/caldav'; import { DAVNamespace } from 'tsdav'; export default async function handler(req, res) { if (req.method === 'GET') { if(req.query.caldav_account_id!=null && req.query.calendar_id!=null) { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if( await middleWareForAuthorisation(req,res)) { var calendarObjects = null - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + + // var userid = await getUseridFromUserhash(userHash[0]) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } - var userid = await getUseridFromUserhash(userHash[0]) var calendar=await checkifUserHasAccesstoRequestedCalendar(userid, req.query.caldav_account_id, req.query.calendar_id) if(calendar!=null) { diff --git a/src/pages/api/caldav/calendars/events/refresh.js b/src/pages/api/caldav/calendars/events/refresh.js index a1743ad..e8fe787 100644 --- a/src/pages/api/caldav/calendars/events/refresh.js +++ b/src/pages/api/caldav/calendars/events/refresh.js @@ -1,16 +1,23 @@ import { getCaldavClient, saveCalendarEventsintoDB } from '@/helpers/api/cal/caldav'; import { getCaldavAccountsfromUserid, getCalendarsfromCaldavAccountsID } from '@/helpers/api/cal/calendars'; import { updateLabels } from '@/helpers/api/cal/labels'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req.headers.authorization)) { if(req.query.caldav_accounts_id!=null) { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + + // var userid = await getUseridFromUserhash(userHash[0]) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + - var userid = await getUseridFromUserhash(userHash[0]) var calendarObjectsArray = [] var caldav_accounts= await getCaldavAccountsfromUserid(userid) diff --git a/src/pages/api/caldav/calendars/index.js b/src/pages/api/caldav/calendars/index.js index 2c3b4b5..c6fe1c5 100644 --- a/src/pages/api/caldav/calendars/index.js +++ b/src/pages/api/caldav/calendars/index.js @@ -1,14 +1,18 @@ import { getCalendarsfromCaldavAccountsID, getCaldavAccountsfromUserid } from "@/helpers/api/cal/calendars" import { getCaldavAccountfromUserID } from '@/helpers/api/cal/calendars'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req, res)) { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) - var userid = await getUseridFromUserhash(userHash[0]) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var final_caldav_account_array=[] var caldav_accounts= await getCaldavAccountsfromUserid(userid) if(caldav_accounts!=null&&Array.isArray(caldav_accounts)&&caldav_accounts.length>0) diff --git a/src/pages/api/caldav/calendars/labels/index.js b/src/pages/api/caldav/calendars/labels/index.js index a20f96a..838feef 100644 --- a/src/pages/api/caldav/calendars/labels/index.js +++ b/src/pages/api/caldav/calendars/labels/index.js @@ -1,13 +1,18 @@ import { getCaldavAccountfromUserID } from '@/helpers/api/cal/calendars'; import { getAllLablesFromDB } from '@/helpers/api/cal/labels'; import { User } from '@/helpers/api/classes/User'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { - var userid=await User.idFromAuthorisation(req.headers.authorization) - + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + const labels = await getAllLablesFromDB(userid) res.status(200).json({ success: true, data: { message: labels} }) diff --git a/src/pages/api/caldav/calendars/modify/object.js b/src/pages/api/caldav/calendars/modify/object.js index fcdcdcb..54238f0 100644 --- a/src/pages/api/caldav/calendars/modify/object.js +++ b/src/pages/api/caldav/calendars/modify/object.js @@ -1,5 +1,5 @@ import { getObjectFromDB, insertObjectIntoDB, updateObjectinDB } from '@/helpers/api/cal/object'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; import { checkifUserHasAccesstoRequestedCalendar, getCaldavAccountIDFromCalendarID } from '@/helpers/api/cal/calendars'; import { getRandomString } from '@/helpers/crypto'; import { updateEventinCalDAVAccount } from '@/helpers/api/cal/caldav'; @@ -9,14 +9,20 @@ import { logVar } from '@/helpers/general'; export default async function handler(req, res) { logVar(req.body, "modify object API CALL") if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.body.url!=null && req.body.url.trim()!="" && req.body.etag!=null && req.body.etag.trim()!="" && req.body.data!=null && req.body.data.trim()!="" && req.body.updated!=null && req.body.updated.toString().trim()!="" && req.body.type!=null && req.body.type.trim()!="" && req.body.deleted!=null && req.body.calendar_id!=null && req.body.calendar_id.trim()!="") { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + + // var userid = await getUseridFromUserhash(userHash[0]) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } - var userid = await getUseridFromUserhash(userHash[0]) var caldav_accounts_id= await getCaldavAccountIDFromCalendarID(req.body.calendar_id) //First we check if user has access to calendar. var calendarFromDB= await checkifUserHasAccesstoRequestedCalendar(userid, caldav_accounts_id,req.body.calendar_id) diff --git a/src/pages/api/caldav/calendars/name.js b/src/pages/api/caldav/calendars/name.js index 27de336..b081261 100644 --- a/src/pages/api/caldav/calendars/name.js +++ b/src/pages/api/caldav/calendars/name.js @@ -1,16 +1,22 @@ import { getCaldavAccountDetailsfromId } from "@/helpers/api/cal/caldav" import { checkifUserHasAccesstoRequestedCalendar, getCaldavAccountsfromUserid } from "@/helpers/api/cal/calendars" -import { getUserHashSSIDfromAuthorisation, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserHashSSIDfromAuthorisation, getUserIDFromLogin, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.query.caldav_accounts_id!=null && req.query.calendars_id!=null && req.query.calendars_id!="" && req.query.caldav_accounts_id!="") { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) - var userid = await getUseridFromUserhash(userHash[0]) + // var userid = await getUseridFromUserhash(userHash[0]) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var allCalendarEvents =null var calendar=await checkifUserHasAccesstoRequestedCalendar(userid, req.query.caldav_accounts_id, req.query.calendars_id) var caldavDetails= await getCaldavAccountDetailsfromId(req.query.caldav_accounts_id) diff --git a/src/pages/api/caldav/calendars/sync/all.js b/src/pages/api/caldav/calendars/sync/all.js index 81888d0..c55790b 100644 --- a/src/pages/api/caldav/calendars/sync/all.js +++ b/src/pages/api/caldav/calendars/sync/all.js @@ -1,18 +1,25 @@ import { getCaldavAccountDetailsfromId } from "@/helpers/api/cal/caldav" import { checkifCalendarExistforUser, deleteCalendarFromDB, getCaldavAccountsAllData, getCaldavAccountsfromUserid, getCalendarsfromCaldavAccountsID, insertCalendarintoDB, updateCalendarinDB } from "@/helpers/api/cal/calendars" import { getCalendarObjectsFromCalendarbyType } from "@/helpers/api/cal/object" -import { getUserHashSSIDfromAuthorisation, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserHashSSIDfromAuthorisation, getUserIDFromLogin, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" import { isValidResultArray } from "@/helpers/general" import { AES } from "crypto-js" import { createDAVClient } from "tsdav" import CryptoJS from "crypto-js" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + + // var userid = await getUseridFromUserhash(userHash[0]) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + - var userid = await getUseridFromUserhash(userHash[0]) var allCaldavAccountBasicData = await getCaldavAccountsAllData(userid) if(isValidResultArray(allCaldavAccountBasicData)) { diff --git a/src/pages/api/caldav/calendars/sync/one.js b/src/pages/api/caldav/calendars/sync/one.js index 1064779..c0a71b7 100644 --- a/src/pages/api/caldav/calendars/sync/one.js +++ b/src/pages/api/caldav/calendars/sync/one.js @@ -1,21 +1,28 @@ import { getCaldavAccountDetailsfromId } from "@/helpers/api/cal/caldav" import { getCaldavAccountsAllData, getCaldavAccountsfromUserid, getCalendarsfromCaldavAccountsID } from "@/helpers/api/cal/calendars" import { getCalendarObjectsFromCalendarbyType } from "@/helpers/api/cal/object" -import { getUserHashSSIDfromAuthorisation, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserHashSSIDfromAuthorisation, getUserIDFromLogin, getUseridFromUserhash, middleWareForAuthorisation } from "@/helpers/api/user" import { isValidResultArray } from "@/helpers/general" import { AES } from "crypto-js" import { createDAVClient } from "tsdav" import CryptoJS from "crypto-js" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.query.calendar_id!=null) { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + + // var userid = await getUseridFromUserhash(userHash[0]) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + - var userid = await getUseridFromUserhash(userHash[0]) var allCaldavAccountBasicData = await getCaldavAccountsAllData(userid) if(isValidResultArray(allCaldavAccountBasicData)) { diff --git a/src/pages/api/caldav/delete.js b/src/pages/api/caldav/delete.js index 7d1b143..9af7c81 100644 --- a/src/pages/api/caldav/delete.js +++ b/src/pages/api/caldav/delete.js @@ -1,15 +1,21 @@ -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { User } from '@/helpers/api/classes/User'; import { CaldavAccount } from "@/helpers/api/classes/CaldavAccount"; import { Calendars } from "@/helpers/api/classes/Calendars"; export default async function handler(req, res) { if (req.method === 'DELETE') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if( await middleWareForAuthorisation(req,res)) { if(req.query.caldav_account_id!=null &&req.query.caldav_account_id!=""&&req.query.caldav_account_id!=undefined) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var user = new User(userid) var userHasAcess= await user.hasAccesstoCaldavAccountID(req.query.caldav_account_id) if (userHasAcess) diff --git a/src/pages/api/caldav/event/delete.js b/src/pages/api/caldav/event/delete.js index b7f7c02..6d09174 100644 --- a/src/pages/api/caldav/event/delete.js +++ b/src/pages/api/caldav/event/delete.js @@ -2,19 +2,25 @@ import { createEventinCalDAVAccount, getCaldavAccountDetailsfromId } from '@/hel import { checkifUserHasAccesstoRequestedCalendar, getCaldavAccountfromUserID, getCaldavAccountIDFromCalendarID, getCalendarfromCalendarID } from '@/helpers/api/cal/calendars'; import { getAllLablesFromDB } from '@/helpers/api/cal/labels'; import { deleteCalendarObjectsFromDB, getObjectFromDB, insertObjectIntoDB, updateObjectinDB } from '@/helpers/api/cal/object'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; import { getRandomString } from '@/helpers/crypto'; import { AES } from 'crypto-js'; import { createDAVClient, deleteCalendarObject } from 'tsdav'; import CryptoJS from 'crypto-js'; export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if( await middleWareForAuthorisation(req,res)) { if(req.body.etag!=null && req.body.etag.trim()!="" && req.body.calendar_id!=null && req.body.calendar_id.toString().trim()!=""&&req.body.url!=null && req.body.url.trim()!="") { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) - var userid = await getUseridFromUserhash(userHash[0]) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userid = await getUseridFromUserhash(userHash[0]) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var currentCaldavAccountID=await getCaldavAccountIDFromCalendarID(req.body.calendar_id) var currentCalendar= await checkifUserHasAccesstoRequestedCalendar(userid, currentCaldavAccountID, req.body.calendar_id) if(currentCalendar!=null) diff --git a/src/pages/api/caldav/index.js b/src/pages/api/caldav/index.js index 6a2759c..eeb9fee 100644 --- a/src/pages/api/caldav/index.js +++ b/src/pages/api/caldav/index.js @@ -1,11 +1,17 @@ import { getCaldavAccountfromUserID } from '@/helpers/api/cal/calendars'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if( await middleWareForAuthorisation(req,res)) { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) - var userid=await getUseridFromUserhash(userHash[0]) + // var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) + // var userid=await getUseridFromUserhash(userHash[0]) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + const caldavAccounts =await getCaldavAccountfromUserID(userid) res.status(200).json({ success: true, data: { message: caldavAccounts} }) diff --git a/src/pages/api/caldav/register.js b/src/pages/api/caldav/register.js index 323beba..69d423f 100644 --- a/src/pages/api/caldav/register.js +++ b/src/pages/api/caldav/register.js @@ -2,21 +2,26 @@ import validator from 'validator'; import { createDAVClient, DAVClient, getBasicAuthHeaders } from 'tsdav'; import { caldavAccountExistinDB, insertCalendarsintoDB, isValidCaldavAccount, getCaldavAccountfromDetails, insertCalendarintoDB, checkifCalendarExistforUser } from '@/helpers/api/cal/calendars' import { getConnectionVar } from '@/helpers/api/db'; -import { middleWareForAuthorisation, getUseridFromUserhash, getUserHashSSIDfromAuthorisation } from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash, getUserHashSSIDfromAuthorisation, getUserIDFromLogin } from '@/helpers/api/user'; import { createCalDAVAccount } from '@/helpers/api/cal/caldav'; import { AES } from 'crypto-js'; import { logError, logVar } from '@/helpers/general'; export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + if(req.query.url!=null && req.query.username!=null && req.query.accountname!=null &&req.query.password!=null) { if ((req.query.url!=null&&validator.isURL(req.query.url)) || req.query.url.startsWith("http://localhost") || req.query.url.startsWith("https://localhost") ){ if(req.query.username!=null&&req.query.password!=null) { - var userHash= await getUserHashSSIDfromAuthorisation(req.headers.authorization) var url = req.query.url var username = validator.escape(req.query.username) @@ -33,7 +38,7 @@ export default async function handler(req, res) { defaultAccountType: 'caldav', }).catch((reason)=>{ logError(reason, "api/caldav/register client:") - res.status(401).json({ success: false, data: {message: reason.message}}) + return res.status(401).json({ success: false, data: {message: reason.message}}) }) @@ -43,7 +48,9 @@ export default async function handler(req, res) { //Caldav authentication was succesful. We'll save the details in the db now. if(calendars!=null) { - var answer= await saveDatatoDatabase(accountname, username, password, url, calendars, userHash[0]) + + + var answer= await saveDatatoDatabase(accountname, username, password, url, calendars, userid) res.status(200).json({ success: true, data: answer}) }else @@ -96,10 +103,9 @@ export default async function handler(req, res) { } } -async function saveDatatoDatabase(accountname, username, password, url, calendars,userhash) +async function saveDatatoDatabase(accountname, username, password, url, calendars,userid) { - var userid = await getUseridFromUserhash(userhash) var calDavAccountIsInDb=await caldavAccountExistinDB(username, url) if(calDavAccountIsInDb==false || (calDavAccountIsInDb!=null&&calDavAccountIsInDb.length==0)) { diff --git a/src/pages/api/calendars/create.js b/src/pages/api/calendars/create.js index 9e8e70e..46c16fd 100644 --- a/src/pages/api/calendars/create.js +++ b/src/pages/api/calendars/create.js @@ -1,7 +1,7 @@ import { CaldavAccount } from "@/helpers/api/classes/CaldavAccount" import { Calendars } from "@/helpers/api/classes/Calendars" import { User } from "@/helpers/api/classes/User" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { addTrailingSlashtoURL, getRandomColourCode, isValidResultArray, replaceSpacewithHyphen } from "@/helpers/general" import { AES } from "crypto-js" import { createDAVClient } from "tsdav" @@ -9,11 +9,18 @@ import CryptoJS from "crypto-js" export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.body.caldav_accounts_id!=null && req.body.caldav_accounts_id!=""&&req.body.calendarName!=null&&req.body.calendarName!="") { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var user = new User(userid) var caldav_accounts= await user.getCaldavAccountsAllData() var caldavAccountFound=-1 diff --git a/src/pages/api/calendars/refresh.js b/src/pages/api/calendars/refresh.js index b7257f7..9c0835c 100644 --- a/src/pages/api/calendars/refresh.js +++ b/src/pages/api/calendars/refresh.js @@ -1,7 +1,7 @@ import { CaldavAccount } from "@/helpers/api/classes/CaldavAccount" import { Calendars } from "@/helpers/api/classes/Calendars" import { User } from "@/helpers/api/classes/User" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { isValidResultArray, logVar } from "@/helpers/general" import { AES } from "crypto-js" import { createDAVClient } from "tsdav" @@ -9,9 +9,16 @@ import CryptoJS from "crypto-js" const LOGTAG = "api/calendars/refresh" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var user = new User(userid) var caldav_accounts= await user.getCaldavAccountsAllData() var finalResponse= [] diff --git a/src/pages/api/events/fetchOne.js b/src/pages/api/events/fetchOne.js index 5082ebc..224675b 100644 --- a/src/pages/api/events/fetchOne.js +++ b/src/pages/api/events/fetchOne.js @@ -1,14 +1,20 @@ import { Calendars } from "@/helpers/api/classes/Calendars" import { User } from "@/helpers/api/classes/User" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.query.calendar_id!=null && req.query.calendar_id!=""&&req.query.url!=null&&req.query.url!=""&&req.query.caldav_accounts_id!=null && req.query.caldav_accounts_id!="") { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var user = new User(userid) var calendar=await Calendars.getFromID(req.query.calendar_id) if(calendar!=null && calendar.calendars_id!=null) diff --git a/src/pages/api/events/search.js b/src/pages/api/events/search.js index 72670e9..009f166 100644 --- a/src/pages/api/events/search.js +++ b/src/pages/api/events/search.js @@ -1,18 +1,25 @@ import { CaldavAccount } from "@/helpers/api/classes/CaldavAccount" import { Calendars } from "@/helpers/api/classes/Calendars" import { User } from "@/helpers/api/classes/User" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { returnGetParsedVTODO } from "@/helpers/frontend/calendar" import { applyTaskFilter, majorTaskFilter } from "@/helpers/frontend/events" import { haystackHasNeedle } from "@/helpers/general" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.query.calendar_id!=null && req.query.calendar_id!=""&& req.query.calendar_id!=undefined && req.query.search_term!="" && req.query.search_term!=undefined && req.query.search_term!=null) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var user = new User(userid) var calendarObject= {calendars_id: req.query.calendar_id} var caldav_id = await CaldavAccount.getIDFromCalendar(calendarObject) diff --git a/src/pages/api/filters/add.js b/src/pages/api/filters/add.js index b24f40c..d47eca0 100644 --- a/src/pages/api/filters/add.js +++ b/src/pages/api/filters/add.js @@ -1,14 +1,19 @@ import { User } from '@/helpers/api/classes/User'; import { insertNewFiltertoDB } from '@/helpers/api/filter'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; import validator from 'validator'; export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if( await middleWareForAuthorisation(req,res)) { if(req.body.name!=null && req.body.name!=""&&req.body.filtervalue!=null&&req.body.filtervalue!="") { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } var jsonToInsert = JSON.stringify(req.body.filtervalue) var dbInsertResponse = insertNewFiltertoDB(req.body.name, jsonToInsert, userid) res.status(200).json({ success: true, data: { message: "FILTER_INSERT_OK"} }) diff --git a/src/pages/api/filters/delete.js b/src/pages/api/filters/delete.js index 1565e5b..595c9b6 100644 --- a/src/pages/api/filters/delete.js +++ b/src/pages/api/filters/delete.js @@ -1,14 +1,19 @@ import { Filters } from '@/helpers/api/classes/Filters'; import { User } from '@/helpers/api/classes/User'; import { getFiltersFromDB } from '@/helpers/api/filter'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; export default async function handler(req, res) { if (req.method === 'DELETE') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.query.filterid!=null &&req.query.filterid!=""&&req.query.filterid!=undefined) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } var filterObject= new Filters(req.query.filterid) diff --git a/src/pages/api/filters/get.js b/src/pages/api/filters/get.js index eefcc43..b3bc433 100644 --- a/src/pages/api/filters/get.js +++ b/src/pages/api/filters/get.js @@ -1,12 +1,17 @@ -import { User } from '@/helpers/api/classes/User'; import { getFiltersFromDB } from '@/helpers/api/filter'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req, res)) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var allLabels= await getFiltersFromDB(userid) res.status(200).json({ success: true, data: { message: allLabels} }) diff --git a/src/pages/api/filters/modify.js b/src/pages/api/filters/modify.js index 813cb42..3a96512 100644 --- a/src/pages/api/filters/modify.js +++ b/src/pages/api/filters/modify.js @@ -1,15 +1,20 @@ import { User } from '@/helpers/api/classes/User'; import { insertNewFiltertoDB, updateFilterinDB } from '@/helpers/api/filter'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; import validator from 'validator'; export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { - console.log(req.body) if(req.body.custom_filters_id!=undefined && req.body.custom_filters_id!=null && req.body.custom_filters_id!="" && req.body.name!=undefined && req.body.name!=null && req.body.name!="" && req.body.filtervalue!=null&&req.body.filtervalue!="") { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var jsonToInsert = JSON.stringify(req.body.filtervalue) var dbInsertResponse = await updateFilterinDB(req.body.custom_filters_id, req.body.name, jsonToInsert, userid) var response = "FILTER_UPDATE_OK" diff --git a/src/pages/api/labels/modifycolor.js b/src/pages/api/labels/modifycolor.js index 95a8efe..2a0ab00 100644 --- a/src/pages/api/labels/modifycolor.js +++ b/src/pages/api/labels/modifycolor.js @@ -1,11 +1,16 @@ import { modifyLabelColour, updateLabels } from '@/helpers/api/cal/labels'; import { User } from '@/helpers/api/classes/User'; -import { middleWareForAuthorisation, } from '@/helpers/api/user'; +import { getUserIDFromLogin, middleWareForAuthorisation, } from '@/helpers/api/user'; export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if( await middleWareForAuthorisation(req,res)) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + if(req.body.labelname!=null &&req.body.labelname!=""&&req.body.labelname!=undefined && req.body.colour!=null &&req.body.colour!=""&&req.body.colour!=undefined) { diff --git a/src/pages/api/labels/updatecache.js b/src/pages/api/labels/updatecache.js index 136ddbb..f23ef29 100644 --- a/src/pages/api/labels/updatecache.js +++ b/src/pages/api/labels/updatecache.js @@ -1,11 +1,16 @@ import { updateLabels } from '@/helpers/api/cal/labels'; -import { User } from '@/helpers/api/classes/User'; -import { middleWareForAuthorisation, } from '@/helpers/api/user'; +import { getUserIDFromLogin, middleWareForAuthorisation, } from '@/helpers/api/user'; export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + const labels = await updateLabels(userid) res.status(200).json({ success: true, data: { message: "LABELS_UPDATED"} }) diff --git a/src/pages/api/misc/generateics.js b/src/pages/api/misc/generateics.js index 83e1ff6..d0f6242 100644 --- a/src/pages/api/misc/generateics.js +++ b/src/pages/api/misc/generateics.js @@ -6,7 +6,7 @@ import moment from "moment" export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(varNotEmpty(req.body.obj)) { diff --git a/src/pages/api/misc/parseics.js b/src/pages/api/misc/parseics.js index 033a093..5d8ff15 100644 --- a/src/pages/api/misc/parseics.js +++ b/src/pages/api/misc/parseics.js @@ -2,7 +2,7 @@ import { middleWareForAuthorisation } from "@/helpers/api/user" export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { var icalToolkit = require('ical-toolkit'); var json = icalToolkit.parseToJSON(req.body.ics); diff --git a/src/pages/api/misc/parseics_ical.js b/src/pages/api/misc/parseics_ical.js index 5522085..f77499d 100644 --- a/src/pages/api/misc/parseics_ical.js +++ b/src/pages/api/misc/parseics_ical.js @@ -3,7 +3,7 @@ import ICAL from '@/../ical.js/build/ical' import { isValidResultArray, logError, varNotEmpty } from "@/helpers/general"; export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { var type="vevent" var dataICS= req.body.ics diff --git a/src/pages/api/settings/get.js b/src/pages/api/settings/get.js index ca9f3a6..19e36f4 100644 --- a/src/pages/api/settings/get.js +++ b/src/pages/api/settings/get.js @@ -1,15 +1,21 @@ import Settings from "@/helpers/api/classes/Settings" import { User } from "@/helpers/api/classes/User" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { varNotEmpty } from "@/helpers/general" import moment from "moment" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var userObj = new User(userid) var isAdmin= await userObj.isAdmin() var settingKeys = await Settings.getAllforUserid(userid) diff --git a/src/pages/api/settings/getone.js b/src/pages/api/settings/getone.js index 7cb2678..d4a83c9 100644 --- a/src/pages/api/settings/getone.js +++ b/src/pages/api/settings/getone.js @@ -1,17 +1,23 @@ import Settings from "@/helpers/api/classes/Settings" import { User } from "@/helpers/api/classes/User" import { getICS } from "@/helpers/api/ical" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { varNotEmpty } from "@/helpers/general" import moment from "moment" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(varNotEmpty(req.query.name)&& req.query.name!="") { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var userObj = new User(userid) var isGlobal =false if(req.query.name.startsWith("GLOBAL_")) diff --git a/src/pages/api/settings/modify.js b/src/pages/api/settings/modify.js index 2eea940..111e3a4 100644 --- a/src/pages/api/settings/modify.js +++ b/src/pages/api/settings/modify.js @@ -1,17 +1,22 @@ import Settings from "@/helpers/api/classes/Settings" import { User } from "@/helpers/api/classes/User" import { getICS } from "@/helpers/api/ical" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { varNotEmpty } from "@/helpers/general" import moment from "moment" export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { //console.log(req.body) if(varNotEmpty(req.body.name) && req.body.name.toString().trim()!="" && varNotEmpty(req.body.value) && req.body.value.toString().trim()!=""){ - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } var userObj = new User(userid) var isGlobal =false diff --git a/src/pages/api/tasks/rrule/getrepeatobj.js b/src/pages/api/tasks/rrule/getrepeatobj.js index 912128d..ee55fbf 100644 --- a/src/pages/api/tasks/rrule/getrepeatobj.js +++ b/src/pages/api/tasks/rrule/getrepeatobj.js @@ -3,15 +3,21 @@ import { Events } from '@/helpers/api/classes/Events'; import { Filters } from '@/helpers/api/classes/Filters'; import { User } from '@/helpers/api/classes/User'; import { getFiltersFromDB } from '@/helpers/api/filter'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.query.calendar_event_id!=null &&req.query.calendar_event_id!=""&&req.query.calendar_event_id!=undefined) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var metaObject = new EventMeta({calendar_events_id: req.query.calendar_event_id, userid: userid, property: "REPEAT_META"}) const userHasAccess = await metaObject.userHasAccess(userid) diff --git a/src/pages/api/tasks/rrule/postrepeatobj.js b/src/pages/api/tasks/rrule/postrepeatobj.js index 138fe8b..7a6d336 100644 --- a/src/pages/api/tasks/rrule/postrepeatobj.js +++ b/src/pages/api/tasks/rrule/postrepeatobj.js @@ -1,16 +1,22 @@ import EventMeta from '@/helpers/api/classes/EventMeta'; import { Events } from '@/helpers/api/classes/Events'; import { User } from '@/helpers/api/classes/User'; -import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation} from '@/helpers/api/user'; +import { middleWareForAuthorisation, getUseridFromUserhash , getUserHashSSIDfromAuthorisation, getUserIDFromLogin} from '@/helpers/api/user'; import { logVar, varNotEmpty } from '@/helpers/general'; export default async function handler(req, res) { if (req.method === 'POST') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { if(req.body.calendar_event_id!=null &&req.body.calendar_event_id!=""&&req.body.calendar_event_id!=undefined && varNotEmpty(req.body.value) && req.body.value!="") { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + const userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var metaObject = new EventMeta({calendar_events_id: req.body.calendar_event_id, userid: userid, property: "REPEAT_META", value:req.body.value}) const userHasAccess = await metaObject.userHasAccess(userid) diff --git a/src/pages/api/users/info.js b/src/pages/api/users/info.js index 8e4fa85..fe2a2c0 100644 --- a/src/pages/api/users/info.js +++ b/src/pages/api/users/info.js @@ -1,14 +1,20 @@ import { User } from "@/helpers/api/classes/User" import { getICS } from "@/helpers/api/ical" -import { middleWareForAuthorisation } from "@/helpers/api/user" +import { getUserIDFromLogin, middleWareForAuthorisation } from "@/helpers/api/user" import { varNotEmpty } from "@/helpers/general" import moment from "moment" export default async function handler(req, res) { if (req.method === 'GET') { - if(req.headers.authorization!=null && await middleWareForAuthorisation(req.headers.authorization)) + if(await middleWareForAuthorisation(req,res)) { - var userid=await User.idFromAuthorisation(req.headers.authorization) + // var userid=await User.idFromAuthorisation(req.headers.authorization) + var userid = await getUserIDFromLogin(req, res) + if(userid==null){ + return res.status(401).json({ success: false, data: { message: 'PLEASE_LOGIN'} }) + + } + var userObj = new User(userid) var userInfo = await userObj.getInfo() res.status(200).json( {success: true, data: {message: userInfo}}) diff --git a/src/pages/api/users/register.js b/src/pages/api/users/register.js index 0381919..1bd8b2b 100644 --- a/src/pages/api/users/register.js +++ b/src/pages/api/users/register.js @@ -26,6 +26,8 @@ export default async function handler(req, res) { { //User is not in db. Register user. var response = await insertUserIntoDB(req.body.username, req.body.password, req.body.email) + + console.log("response" ,response) if(response){ res.status(200).json({ success: response ,data: {message: "USER_INSERT_OK"} }) diff --git a/src/pages/calendar/view.tsx b/src/pages/calendar/view.tsx new file mode 100644 index 0000000..416cfc9 --- /dev/null +++ b/src/pages/calendar/view.tsx @@ -0,0 +1,35 @@ +import CalendarView from "@/components/page/CalendarViewPage/CalendarView"; +import { checkLogin_InBuilt } from "@/helpers/frontend/user"; +import { nextAuthEnabled } from "@/helpers/thirdparty/nextAuth"; +import { signIn, useSession } from "next-auth/react"; +import { useRouter } from "next/router"; +import { useEffect } from "react"; + + +export default function CalendarViewPage(){ + const { data: session, status } = useSession() + const router = useRouter() + + useEffect(() =>{ + + if(nextAuthEnabled()){ + if (status=="unauthenticated" ) { + signIn() + } + }else{ + // Check login using inbuilt function. + + checkLogin_InBuilt(router, "/calendar/view") + } + }, [status,router]) + + + + + + return( + <> + + + ) +} \ No newline at end of file diff --git a/src/pages/filters/manage.tsx b/src/pages/filters/manage.tsx new file mode 100644 index 0000000..46404cc --- /dev/null +++ b/src/pages/filters/manage.tsx @@ -0,0 +1,35 @@ +import CalendarView from "@/components/page/CalendarViewPage/CalendarView"; +import ManageFilters from "@/components/page/ManageFiltersPage/ManageFilters"; +import { checkLogin_InBuilt } from "@/helpers/frontend/user"; +import { nextAuthEnabled } from "@/helpers/thirdparty/nextAuth"; +import { signIn, useSession } from "next-auth/react"; +import { useRouter } from "next/router"; +import { useEffect } from "react"; + + +export default function ManageViewPage(){ + const { data: session, status } = useSession() + const router = useRouter() + + useEffect(() =>{ + if(nextAuthEnabled()){ + if (status=="unauthenticated" ) { + signIn() + } + }else{ + // Check login using inbuilt function. + + checkLogin_InBuilt(router, "/filters/manage") + } + }, [status, router]) + + + + + + return( + <> + + + ) +} \ No newline at end of file diff --git a/src/pages/index.js b/src/pages/index.js index 2d77017..518b924 100644 --- a/src/pages/index.js +++ b/src/pages/index.js @@ -1,46 +1,67 @@ import Head from 'next/head' -import TaskList from '@/components/tasks/TaskList' -import AppBarGeneric from '@/components/common/AppBarGeneric' -import { Col, Row } from 'react-bootstrap' -import { getTodaysDateUnixTimeStamp, varNotEmpty } from '@/helpers/general' -import DashboardView from '@/components/fullcalendar/DashboardView' -import AddTask from '@/components/common/AddTask/AddTask' -import { PRIMARY_COLOUR, SECONDARY_COLOUR } from '@/config/style' -import { Component, useEffect, useState } from 'react' +import AppBarGeneric from '@/components/common/AppBar' +import { useEffect, useState, useRef } from 'react' import { getI18nObject } from '@/helpers/frontend/general' -import { MYDAY_LABEL } from '@/config/constants' -import Offcanvas from 'react-bootstrap/Offcanvas'; -import { AiOutlineMenuUnfold } from 'react-icons/ai' -import Script from 'next/script' -import HomeTasks from '@/components/Home/HomeTasks/HomeTasks' import CombinedView from '@/components/page/CombinedView' -import { Loading } from '@/components/common/Loading' +import { useSession, signIn } from "next-auth/react" +import { nextAuthEnabled } from '@/helpers/thirdparty/nextAuth' +import { checkLogin_InBuilt, logoutUser_withRedirect } from '@/helpers/frontend/user' +import { varNotEmpty } from '@/helpers/general' +import { useRouter } from 'next/router' const i18next = getI18nObject() - export default function HomePage() { + const { data: session, status } = useSession() const [updated, setUpdated]=useState('') const [isSyncing, setIsSyncing] = useState(false) - const onSynComplete = () =>{ var updated = Math.floor(Date.now() / 1000) setUpdated(updated) } - const [finalOutput, setFinalOutput] =useState() + //const [finalOutput, setFinalOutput] =useState() + // useEffect(()=>{ + + + // // if(!loginChecked.current){ + // // loginChecked.current=true + // // const checkAuth = async() =>{ + // // const auth = await isUserLoggedIn() + // // if(auth){ + // // setUserAuthenticated(true) + // // } + // // } + // // checkAuth() + // // } + + // // }, [userAuthenticated]) + const router = useRouter() + + useEffect(() =>{ + if(nextAuthEnabled()){ + if (status=="unauthenticated" ) { + signIn() + } + }else{ + // Check login using inbuilt function. + checkLogin_InBuilt(router) + } + }, [status, router]) + + + + var finalOutput = () - useEffect(()=>{ - }) return( <> - {i18next.t("APP_NAME_TITLE")} - {i18next.t("TASKS")} + {i18next.t("APP_NAME_TITLE")} - {i18next.t("HOME")}
- {finalOutput} + {finalOutput}
diff --git a/src/pages/labels/manage.tsx b/src/pages/labels/manage.tsx new file mode 100644 index 0000000..4c42a5d --- /dev/null +++ b/src/pages/labels/manage.tsx @@ -0,0 +1,35 @@ +import ManageLabels from "@/components/page/MangerLabelsPage/ManageLabels"; +import { checkLogin_InBuilt } from "@/helpers/frontend/user"; +import { nextAuthEnabled } from "@/helpers/thirdparty/nextAuth"; +import { signIn, useSession } from "next-auth/react"; +import { useRouter } from "next/router"; +import { useEffect } from "react"; + + +export default function ManageLabelsPage(){ + const { data: session, status } = useSession() + const router = useRouter() + + useEffect(() =>{ + + if(nextAuthEnabled()){ + if (status=="unauthenticated" ) { + signIn() + } + }else{ + // Check login using inbuilt function. + + checkLogin_InBuilt(router, "/labels/manage") + } + }, [status, router]) + + + + + + return( + <> + + + ) +} \ No newline at end of file diff --git a/src/pages/tasks/list.tsx b/src/pages/tasks/list.tsx new file mode 100644 index 0000000..d6e5b95 --- /dev/null +++ b/src/pages/tasks/list.tsx @@ -0,0 +1,35 @@ +import TaskViewList from "@/components/page/TaskViewPage/TaskViewList"; +import { checkLogin_InBuilt } from "@/helpers/frontend/user"; +import { nextAuthEnabled } from "@/helpers/thirdparty/nextAuth"; +import { signIn, useSession } from "next-auth/react"; +import { useRouter } from "next/router"; +import { useEffect } from "react"; + + +export default function TaskListPage(){ + const { data: session, status } = useSession() + const router = useRouter() + + useEffect(() =>{ + + if(nextAuthEnabled()){ + if (status=="unauthenticated" ) { + signIn() + } + }else{ + // Check login using inbuilt function. + + checkLogin_InBuilt(router, "/tasks/list") + } + }, [status,router]) + + + + + + return( + <> + + + ) +} \ No newline at end of file