Skip to content

Commit

Permalink
Removes environments from auth system and user bundle
Browse files Browse the repository at this point in the history
  • Loading branch information
jcarlosn committed Oct 26, 2024
1 parent b1d7bd2 commit a4681d7
Show file tree
Hide file tree
Showing 4 changed files with 6 additions and 50 deletions.
20 changes: 3 additions & 17 deletions apps/core/src/api/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,14 +33,12 @@ const genNewSession = (data: any) => {

app.post('/api/core/v1/auth/login', handler(async (req: any, res: any) => {
const request: LoginRequest = req.body
const env = req.query.env ?? 'prod'
const fail = (msg) => {
res.status(401).send('"'+msg+'"')
generateEvent({
environment: env,
path: 'auth/login/error', //event type: / separated event category: files/create/file, files/create/dir, devices/device/online
from: 'core', // system entity where the event was generated (next, api, cmd...)
user: 'system', // the original user that generates the action, 'system' if the event originated in the system itself
path: 'auth/login/error',
from: 'core',
user: 'system',
payload: {reason: msg, username: request.username, clientIp: req.get('X-Client-IP') || req.headers['x-client-ip'] } // event payload, event-specific data
}, getServiceToken())
}
Expand All @@ -52,11 +50,6 @@ app.post('/api/core/v1/auth/login', handler(async (req: any, res: any) => {
}

const storedUser = JSON.parse(await db.get(request.username))
const entityModel = UserModel.load(storedUser)

if(!entityModel.hasEnvironment(env)) {
return fail("This user is not registered for this environment")
}

if (await checkPassword(request.password, storedUser.password)) {
//update lastLogin
Expand All @@ -70,7 +63,6 @@ app.post('/api/core/v1/auth/login', handler(async (req: any, res: any) => {
}
const newSession = {
id: storedUser.username,
environments: storedUser.environments,
type: storedUser.type,
admin: group.admin ? true : false,
permissions: [...(group.admin ? ["*"] : []), storedUser.type, ...(group.permissions ?? []), ...(storedUser.permissions ?? [])]
Expand All @@ -80,7 +72,6 @@ app.post('/api/core/v1/auth/login', handler(async (req: any, res: any) => {
context: await getSessionContext(storedUser.type)
})
generateEvent({
environment: env,
path: 'auth/login/success', //event type: / separated event category: files/create/file, files/create/dir, devices/device/online
from: 'core', // system entity where the event was generated (next, api, cmd...)
user: request.username, // the original user that generates the action, 'system' if the event originated in the system itself
Expand Down Expand Up @@ -112,7 +103,6 @@ app.post('/api/core/v1/auth/register', handler(async (req: any, res: any) => {
res.status(403).send('Signup is disabled');
return
}
const env = req.query.env ?? 'prod'
const request: RegisterRequest = req.body
const defaultGroup = "user"
RegisterSchema.parse(request)
Expand All @@ -124,7 +114,6 @@ app.post('/api/core/v1/auth/register', handler(async (req: any, res: any) => {
const newUser = {
...newUserData,
from: 'signup',
environments: [env],
password: await hash(password)
}
const entityModel = UserModel.load(newUser).create()
Expand All @@ -144,11 +133,9 @@ app.post('/api/core/v1/auth/register', handler(async (req: any, res: any) => {
}

generateEvent({
environment: env,
path: 'auth/register/user', //event type: / separated event category: files/create/file, files/create/dir, devices/device/online
from: 'core', // system entity where the event was generated (next, api, cmd...)
user: request.username, // the original user that generates the action, 'system' if the event originated in the system itself
payload: {environments: [req.query.env ?? 'prod']} // event payload, event-specific data
}, getServiceToken())
logger.info({ newUserData }, "User created: " + newUserData.username)

Expand All @@ -158,7 +145,6 @@ app.post('/api/core/v1/auth/register', handler(async (req: any, res: any) => {
type: defaultGroup,
admin: group.admin ? true : false,
permissions: [...(group.admin ? ["*"] : []), defaultGroup, ...(group.permissions ?? [])],
environments: [env]
}
res.send({
session: genNewSession(newSession),
Expand Down
4 changes: 1 addition & 3 deletions apps/core/src/cmd/addUser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ if (process.argv.length < 5) {
const username = process.argv[2]
const password = process.argv[3]
const type = process.argv[4]
const environments = process.argv.length > 5 ? process.argv.slice(5) : ['*']
const dbPath = 'auth'


Expand All @@ -38,8 +37,7 @@ const addUser = async () => {
password: await hash(password),
createdAt: currentDateISO,
from: 'cmd',
type: type,
environments: environments
type: type
}
const entityModel = UserModel.load(userData)
await getDB(dbPath).put(username, JSON.stringify(userData))
Expand Down
24 changes: 0 additions & 24 deletions packages/protobase/src/models/user.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ export const UserSchema = Schema.object({
permissions: z.array(z.string()).optional().label("additional permissions"),
createdAt: z.string().min(1).generate((obj) => moment().toISOString()).search().hidden(["edit", "add"]).indexed(),
lastLogin: z.string().optional().search().hidden(["edit", "add"]).indexed(),
environments: z.array(z.enum(['dev', 'prod', '*'])).optional().help("The environments the user has access to. '*' means all environments").groupIndex("env", "return !data.environments || data.environments.includes('*') ? ['dev', 'prod'] : data.environments"),
from: z.string().min(1).search().generate((obj) => 'admin').help("Interface used to create the user. Users can be created from command line or from the admin panel").hidden(["edit", "add"])
})
export type UserType = z.infer<typeof UserSchema>;
Expand All @@ -19,33 +18,10 @@ export class UserModel extends ProtoModel<UserModel> {
super(data, UserSchema, session, "User");
}

hasEnvironment(env: string) {
return !this.data.environments || this.data.environments.includes('*') || this.data.environments.includes(env)
}

static load(data: any, session?: SessionDataType): UserModel {
return this._newInstance(data, session);
}

list(search?, session?, extraData?, params?): any {
if(params && params.filter && params.filter.environments) {
const {environments, ...filter} = params.filter
if(!this.hasEnvironment(environments)) {
return
}
params = {
...params,
filter: {
...filter,
}
}
}

//pass params with params.filter.environments removed

return super.list(search, session, extraData, params)
}

protected static _newInstance(data: any, session?: SessionDataType): UserModel {
return new UserModel(data, session);
}
Expand Down
8 changes: 2 additions & 6 deletions packages/protolib/src/bundles/users/adminPages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { DataTable2 } from '../../components/DataTable2';
import { Chip } from '../../components/Chip';
import { DataView } from '../../components/DataView';
import { AdminPage } from '../../components/AdminPage';
import { useWorkspaceEnv } from '../../lib/useWorkspaceEnv';
import moment from 'moment';
import { Mail, Tag, Key, User } from '@tamagui/lucide-icons';
import { API } from 'protobase'
Expand All @@ -29,7 +28,6 @@ export default {
component: ({ pageState, initialItems, itemData, pageSession, extraData }: any) => {
const [all, setAll] = useState(false)
const [groups, setGroups] = useState(extraData?.groups ?? getPendingResult("pending"))
const env = useWorkspaceEnv()

usePendingEffect((s) => { API.get(groupsSourceUrl, s) }, setGroups, extraData?.groups)

Expand Down Expand Up @@ -85,7 +83,6 @@ export default {
itemData={itemData}
rowIcon={User}
sourceUrl={sourceUrl}
sourceUrlParams={all ? undefined : { env }}
initialItems={initialItems}
numColumnsForm={1}
name="user"
Expand All @@ -95,7 +92,7 @@ export default {
throw "Passwords do not match"
}
const { repassword, ...finalData } = data
return { ...finalData, environments: data.environments && data.environments.length ? data.environments : [env] }
return finalData
}}
onEdit={data => {
if (data.password != data.repassword) {
Expand All @@ -121,8 +118,7 @@ export default {
DataTable2.column("type", row => row.type, "tyoe", row => <Chip text={row.type?.toUpperCase()} color={row.type == 'admin' ? '$color5' : '$gray5'} />),
DataTable2.column("from", row => row.from, "from", row => <Chip text={row.from?.toUpperCase()} color={row.from == 'cmd' ? '$blue5' : '$gray5'} />),
DataTable2.column("created", row => row.createdAt, "createdAt", row => moment(row.createdAt).format(format)),
DataTable2.column("last login", row => row.lastLogin, "lastLogin", row => row.lastLogin ? <Chip text={moment(row.lastLogin).format(format)} color={'$gray5'} /> : <Chip text={'never'} color={'$gray5'} />),
DataTable2.column("environments", row => row.environments, "environments", row => row.environments ? <XStack>{row.environments.map((env) => <Chip text={env.toUpperCase()} color={env == '*' ? '$orange5' : (env == 'dev' ? '$gray5' : '$color5')} />)}</XStack> : <Chip text={'*'} color={'$orange5'} />)
DataTable2.column("last login", row => row.lastLogin, "lastLogin", row => row.lastLogin ? <Chip text={moment(row.lastLogin).format(format)} color={'$gray5'} /> : <Chip text={'never'} color={'$gray5'} />)
)}
extraFieldsForms={{
repassword: z.string().min(6).label('repeat password').after('password').hint('**********').secret()
Expand Down

0 comments on commit a4681d7

Please sign in to comment.