text stringlengths 1 2.83M | id stringlengths 16 152 | metadata dict | __index_level_0__ int64 0 949 |
|---|---|---|---|
/* eslint-disable
node/handle-callback-err,
max-len,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const { expect } = require('chai')
const async = require('async')
const User = require('./helpers/User')
describe('User Must Reconfirm', function () {
beforeEach(function (done) {
this.user = new User()
return async.series(
[
this.user.ensureUserExists.bind(this.user),
cb => this.user.mongoUpdate({ $set: { must_reconfirm: true } }, cb),
],
done
)
})
it('should not allow sign in', function (done) {
return this.user.login(err => {
expect(err != null).to.equal(false)
return this.user.isLoggedIn((err, isLoggedIn) => {
expect(isLoggedIn).to.equal(false)
return done()
})
})
})
describe('Requesting reconfirmation email', function () {
it('should return a success to client for existing account', function (done) {
return this.user.reconfirmAccountRequest(
this.user.email,
(err, response) => {
expect(err != null).to.equal(false)
expect(response.statusCode).to.equal(200)
return done()
}
)
})
it('should return a 404 to client for non-existent account', function (done) {
return this.user.reconfirmAccountRequest(
'fake@overleaf.com',
(err, response) => {
expect(err != null).to.equal(false)
expect(response.statusCode).to.equal(404)
return done()
}
)
})
})
})
| overleaf/web/test/acceptance/src/UserReconfirmTests.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/UserReconfirmTests.js",
"repo_id": "overleaf",
"token_count": 734
} | 550 |
const OError = require('@overleaf/o-error')
const express = require('express')
const bodyParser = require('body-parser')
/**
* Abstract class for running a mock API via Express. Handles setting up of
* the server on a specific port, and provides an overridable method to
* initialise routes.
*
* Mocks are singletons, and must be initialized with the `initialize` method.
* Instance objects are available via the `instance()` method.
*
* You must override 'reset' and 'applyRoutes' when subclassing this
*
* Wraps the express app's http verb methods for convenience
*
* @hideconstructor
* @member {number} port - the port for the http server
* @member app - the Express application
*/
class AbstractMockApi {
/**
* Create a new API. No not call directly - use the `initialize` method
*
* @param {number} port - The TCP port to start the API on
* @param {object} options - An optional hash of options to modify the behaviour of the mock
* @param {boolean} options.debug - When true, print http requests and responses to stdout
* Set this to 'true' from the constructor of your derived class
*/
constructor(port, { debug } = {}) {
if (!this.constructor._fromInit) {
throw new OError(
'do not create this class directly - use the initialize method',
{ className: this.constructor.name }
)
}
if (this.constructor._obj) {
throw new OError('mock already initialized', {
className: this.constructor._obj.constructor.name,
port: this.port,
})
}
if (this.constructor === AbstractMockApi) {
throw new OError(
'Do not construct AbstractMockApi directly - use a subclass'
)
}
this.debug = debug
this.port = port
this.app = express()
this.app.use(bodyParser.json())
this.app.use(bodyParser.urlencoded({ extended: true }))
}
/**
* Apply debugging routes to print out API activity to stdout
*/
applyDebugRoutes() {
if (!this.debug) return
this.app.use((req, res, next) => {
const { method, path, query, params, body } = req
// eslint-disable-next-line no-console
console.log(`${this.constructor.name} REQUEST`, {
method,
path,
query,
params,
body,
})
const oldEnd = res.end
const oldJson = res.json
res.json = (...args) => {
// eslint-disable-next-line no-console
console.log(`${this.constructor.name} RESPONSE JSON`, args[0])
oldJson.call(res, ...args)
}
res.end = (...args) => {
// eslint-disable-next-line no-console
console.log(`${this.constructor.name} STATUS`, res.statusCode)
if (res.statusCode >= 500) {
// eslint-disable-next-line no-console
console.log('ERROR RESPONSE:', args)
}
oldEnd.call(res, ...args)
}
next()
})
}
/**
* Overridable method to add routes - should be overridden in derived classes
* @abstract
*/
applyRoutes() {
throw new OError(
'AbstractMockApi base class implementation should not be called'
)
}
/**
* Resets member data and restores the API to a clean state for the next test run
* - may be overridden in derived classes
*/
reset() {}
/**
* Applies mocha hooks to start and stop the API at the beginning/end of
* the test suite, and reset before each test run
*
* @param {number} port - The TCP port to start the API on
* @param {object} options - An optional hash of options to modify the behaviour of the mock
* @param {boolean} options.debug - When true, print http requests and responses to stdout
* Set this to 'true' from the constructor of your derived class
*/
static initialize(port, { debug } = {}) {
// `this` refers to the derived class
this._fromInit = true
this._obj = new this(port, { debug })
this._obj.applyDebugRoutes()
this._obj.applyRoutes()
/* eslint-disable mocha/no-mocha-arrows */
const name = this.constructor.name
before(`starting mock ${name}`, () => this._obj.start())
after(`stopping mock ${name}`, () => this._obj.stop())
beforeEach(`resetting mock ${name}`, () => this._obj.reset())
}
/**
* Starts the API on the configured port
*
* @return {Promise<void>}
*/
async start() {
return new Promise((resolve, reject) => {
if (this.debug) {
// eslint-disable-next-line no-console
console.log('Starting mock on port', this.constructor.name, this.port)
}
this.server = this.app
.listen(this.port, err => {
if (err) {
return reject(err)
}
resolve()
})
.on('error', error => {
// eslint-disable-next-line no-console
console.error(
'error starting mock:',
this.constructor.name,
error.message
)
process.exit(1)
})
})
}
/**
* Returns the constructed object
*
* @return {AbstractMockApi}
*/
static instance() {
return this._obj
}
/**
* Shuts down the API and waits for it to stop listening
*
* @return {Promise<void>}
*/
async stop() {
if (!this.server) return
return new Promise((resolve, reject) => {
if (this.debug) {
// eslint-disable-next-line no-console
console.log('Stopping mock', this.constructor.name)
}
this.server.close(err => {
delete this.server
if (err) {
return reject(err)
}
resolve()
})
})
}
}
module.exports = AbstractMockApi
| overleaf/web/test/acceptance/src/mocks/AbstractMockApi.js/0 | {
"file_path": "overleaf/web/test/acceptance/src/mocks/AbstractMockApi.js",
"repo_id": "overleaf",
"token_count": 2253
} | 551 |
import sinon from 'sinon'
import { expect } from 'chai'
import { screen, render, fireEvent } from '@testing-library/react'
import MessageList from '../../../../../frontend/js/features/chat/components/message-list'
import { stubMathJax, tearDownMathJaxStubs } from './stubs'
describe('<MessageList />', function () {
const currentUser = {
id: 'fake_user',
first_name: 'fake_user_first_name',
email: 'fake@example.com',
}
function createMessages() {
return [
{
id: '1',
contents: ['a message'],
user: currentUser,
timestamp: new Date().getTime(),
},
{
id: '2',
contents: ['another message'],
user: currentUser,
timestamp: new Date().getTime(),
},
]
}
before(function () {
stubMathJax()
})
after(function () {
tearDownMathJaxStubs()
})
it('renders multiple messages', function () {
render(
<MessageList
userId={currentUser.id}
messages={createMessages()}
resetUnreadMessages={() => {}}
/>
)
screen.getByText('a message')
screen.getByText('another message')
})
it('renders a single timestamp for all messages within 5 minutes', function () {
const msgs = createMessages()
msgs[0].timestamp = new Date(2019, 6, 3, 4, 23).getTime()
msgs[1].timestamp = new Date(2019, 6, 3, 4, 27).getTime()
render(
<MessageList
userId={currentUser.id}
messages={msgs}
resetUnreadMessages={() => {}}
/>
)
screen.getByText('4:23 am Wed, 3rd Jul 19')
expect(screen.queryByText('4:27 am Wed, 3rd Jul 19')).to.not.exist
})
it('renders a timestamp for each messages separated for more than 5 minutes', function () {
const msgs = createMessages()
msgs[0].timestamp = new Date(2019, 6, 3, 4, 23).getTime()
msgs[1].timestamp = new Date(2019, 6, 3, 4, 31).getTime()
render(
<MessageList
userId={currentUser.id}
messages={msgs}
resetUnreadMessages={() => {}}
/>
)
screen.getByText('4:23 am Wed, 3rd Jul 19')
screen.getByText('4:31 am Wed, 3rd Jul 19')
})
it('resets the number of unread messages after clicking on the input', function () {
const resetUnreadMessages = sinon.stub()
render(
<MessageList
userId={currentUser.id}
messages={createMessages()}
resetUnreadMessages={resetUnreadMessages}
/>
)
fireEvent.click(screen.getByRole('list'))
expect(resetUnreadMessages).to.be.calledOnce
})
})
| overleaf/web/test/frontend/features/chat/components/message-list.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/chat/components/message-list.test.js",
"repo_id": "overleaf",
"token_count": 1053
} | 552 |
import { expect } from 'chai'
import sinon from 'sinon'
import { screen, fireEvent } from '@testing-library/react'
import renderWithContext from '../../helpers/render-with-context'
import FileTreeitemInner from '../../../../../../frontend/js/features/file-tree/components/file-tree-item/file-tree-item-inner'
import FileTreeContextMenu from '../../../../../../frontend/js/features/file-tree/components/file-tree-context-menu'
describe('<FileTreeitemInner />', function () {
const setContextMenuCoords = sinon.stub()
beforeEach(function () {
global.requestAnimationFrame = sinon.stub()
})
afterEach(function () {
setContextMenuCoords.reset()
delete global.requestAnimationFrame
})
describe('menu', function () {
it('does not display if file is not selected', function () {
renderWithContext(
<FileTreeitemInner id="123abc" name="bar.tex" isSelected={false} />,
{}
)
expect(screen.queryByRole('menu', { visible: false })).to.not.exist
})
})
describe('context menu', function () {
it('does not display without write permissions', function () {
renderWithContext(
<FileTreeitemInner id="123abc" name="bar.tex" isSelected />,
{ contextProps: { hasWritePermissions: false } }
)
expect(screen.queryByRole('menu', { visible: false })).to.not.exist
})
it('open / close', function () {
const { container } = renderWithContext(
<>
<FileTreeitemInner id="123abc" name="bar.tex" isSelected />
<FileTreeContextMenu />
</>
)
expect(screen.queryByRole('menu')).to.be.null
// open the context menu
const entityElement = container.querySelector('div.entity')
fireEvent.contextMenu(entityElement)
screen.getByRole('menu', { visible: true })
// close the context menu
fireEvent.click(entityElement)
expect(screen.queryByRole('menu')).to.be.null
})
})
describe('name', function () {
it('renders name', function () {
renderWithContext(
<FileTreeitemInner id="123abc" name="bar.tex" isSelected />
)
screen.getByRole('button', { name: 'bar.tex' })
expect(screen.queryByRole('textbox')).to.not.exist
})
it('starts rename on menu item click', function () {
renderWithContext(
<FileTreeitemInner id="123abc" name="bar.tex" isSelected />,
{
contextProps: {
rootDocId: '123abc',
rootFolder: [
{
_id: 'root-folder-id',
docs: [{ _id: '123abc', name: 'bar.tex' }],
folders: [],
fileRefs: [],
},
],
},
}
)
const toggleButton = screen.getByRole('button', { name: 'Menu' })
fireEvent.click(toggleButton)
const renameButton = screen.getByRole('menuitem', { name: 'Rename' })
fireEvent.click(renameButton)
expect(screen.queryByRole('button', { name: 'bar.tex' })).to.not.exist
screen.getByRole('textbox')
})
})
})
| overleaf/web/test/frontend/features/file-tree/components/file-tree-item/file-tree-item-inner.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/file-tree/components/file-tree-item/file-tree-item-inner.test.js",
"repo_id": "overleaf",
"token_count": 1265
} | 553 |
import { expect } from 'chai'
import sinon from 'sinon'
import { screen, render, fireEvent } from '@testing-library/react'
import OutlineItem from '../../../../../frontend/js/features/outline/components/outline-item'
describe('<OutlineItem />', function () {
const jumpToLine = sinon.stub()
afterEach(function () {
jumpToLine.reset()
})
it('renders basic item', function () {
const outlineItem = {
title: 'Test Title',
line: 1,
}
render(<OutlineItem outlineItem={outlineItem} jumpToLine={jumpToLine} />)
screen.getByRole('treeitem', { current: false })
screen.getByRole('button', { name: outlineItem.title })
expect(screen.queryByRole('button', { name: 'Collapse' })).to.not.exist
})
it('collapses and expands', function () {
const outlineItem = {
title: 'Parent',
line: 1,
children: [{ title: 'Child', line: 2 }],
}
render(<OutlineItem outlineItem={outlineItem} jumpToLine={jumpToLine} />)
const collapseButton = screen.getByRole('button', { name: 'Collapse' })
// test that children are rendered
screen.getByRole('button', { name: 'Child' })
fireEvent.click(collapseButton)
screen.getByRole('button', { name: 'Expand' })
expect(screen.queryByRole('button', { name: 'Child' })).to.not.exist
})
it('highlights', function () {
const outlineItem = {
title: 'Parent',
line: 1,
}
render(
<OutlineItem
outlineItem={outlineItem}
jumpToLine={jumpToLine}
highlightedLine={1}
/>
)
screen.getByRole('treeitem', { current: true })
})
it('highlights when has collapsed highlighted child', function () {
const outlineItem = {
title: 'Parent',
line: 1,
children: [{ title: 'Child', line: 2 }],
}
render(
<OutlineItem
outlineItem={outlineItem}
jumpToLine={jumpToLine}
highlightedLine={2}
/>
)
screen.getByRole('treeitem', { name: 'Parent', current: false })
screen.getByRole('treeitem', { name: 'Child', current: true })
fireEvent.click(screen.getByRole('button', { name: 'Collapse' }))
screen.getByRole('treeitem', { name: 'Parent', current: true })
})
it('click and double-click jump to location', function () {
const outlineItem = {
title: 'Parent',
line: 1,
}
render(<OutlineItem outlineItem={outlineItem} jumpToLine={jumpToLine} />)
const titleButton = screen.getByRole('button', { name: outlineItem.title })
fireEvent.click(titleButton)
expect(jumpToLine).to.be.calledOnce
expect(jumpToLine).to.be.calledWith(1, false)
jumpToLine.reset()
fireEvent.doubleClick(titleButton)
expect(jumpToLine).to.be.calledOnce
expect(jumpToLine).to.be.calledWith(1, true)
})
})
| overleaf/web/test/frontend/features/outline/components/outline-item.test.js/0 | {
"file_path": "overleaf/web/test/frontend/features/outline/components/outline-item.test.js",
"repo_id": "overleaf",
"token_count": 1065
} | 554 |
// Disable prop type checks for test harnesses
/* eslint-disable react/prop-types */
import { render } from '@testing-library/react'
import sinon from 'sinon'
import { UserProvider } from '../../../frontend/js/shared/context/user-context'
import { EditorProvider } from '../../../frontend/js/shared/context/editor-context'
import { LayoutProvider } from '../../../frontend/js/shared/context/layout-context'
import { ChatProvider } from '../../../frontend/js/features/chat/context/chat-context'
import { IdeProvider } from '../../../frontend/js/shared/context/ide-context'
import { get } from 'lodash'
import { ProjectProvider } from '../../../frontend/js/shared/context/project-context'
export function EditorProviders({
user = { id: '123abd' },
projectId = 'project123',
socket = {
on: sinon.stub(),
removeListener: sinon.stub(),
},
isRestrictedTokenMember = false,
scope,
children,
}) {
window.user = user || window.user
window.gitBridgePublicBaseUrl = 'git.overleaf.test'
window.project_id = projectId != null ? projectId : window.project_id
window.isRestrictedTokenMember = isRestrictedTokenMember
const $scope = {
user: window.user,
project: {
_id: window.project_id,
name: 'project-name',
owner: {
_id: '124abd',
email: 'owner@example.com',
},
},
ui: {
chatOpen: true,
pdfLayout: 'flat',
},
$watch: (path, callback) => {
callback(get($scope, path))
return () => null
},
$applyAsync: () => {},
toggleHistory: () => {},
...scope,
}
window._ide = { $scope, socket }
return (
<IdeProvider ide={window._ide}>
<UserProvider>
<ProjectProvider>
<EditorProvider settings={{}}>
<LayoutProvider>{children}</LayoutProvider>
</EditorProvider>
</ProjectProvider>
</UserProvider>
</IdeProvider>
)
}
export function renderWithEditorContext(component, contextProps) {
const EditorProvidersWrapper = ({ children }) => (
<EditorProviders {...contextProps}>{children}</EditorProviders>
)
return render(component, { wrapper: EditorProvidersWrapper })
}
export function ChatProviders({ children, ...props }) {
return (
<EditorProviders {...props}>
<ChatProvider>{children}</ChatProvider>
</EditorProviders>
)
}
export function renderWithChatContext(component, props) {
const ChatProvidersWrapper = ({ children }) => (
<ChatProviders {...props}>{children}</ChatProviders>
)
return render(component, { wrapper: ChatProvidersWrapper })
}
export function cleanUpContext() {
delete window.user
delete window.project_id
delete window._ide
}
| overleaf/web/test/frontend/helpers/render-with-context.js/0 | {
"file_path": "overleaf/web/test/frontend/helpers/render-with-context.js",
"repo_id": "overleaf",
"token_count": 953
} | 555 |
# SmokeTests
For the SmokeTests we implemented a Mini-Framework that is tailored for our
tooling, specifically OError, and does not need a large runner, such as mocha.
The SmokeTests are separated into individual `steps`.
Each `step` can have a `run` function and a `cleanup` function.
The former will run in sequence with the other steps, the later in reverse
order from the finish, or the last failure.
```js
async function run(ctx) {
// do something
}
async function cleanup(ctx) {
// cleanup something
}
module.exports = { cleanup, run }
```
Steps will get called with a context object with common helpers and details:
- `request` a promisified `request` module with defaults for `baseUrl`,
`timeout` and internals for cookie handling.
- `assertHasStatusCode` a helper for asserting response status codes, pass
a response and desired status code. It will throw with OError context set.
- `getCsrfTokenFor` a helper for retrieving CSRF tokens, pass an endpoint.
- `processWithTimeout` a helper for awaiting Promises with a timeout, pass
`{ work: Promise.resolve(), timeout: 42, message: 'foo timedout' }`
- `stats` an object for performance tracking.
- `timeout` the step timeout
Steps should handle timeouts locally to ensure appropriate cleanup of timed out
actions.
Steps may pass values along to the next steps in returning an object with the
desired fields from the `run` or `cleanup` function.
The returned values will overwrite existing details in the `ctx`.
Alpha-numeric sorting of step filenames determines the processing sequence.
| overleaf/web/test/smoke/src/README.md/0 | {
"file_path": "overleaf/web/test/smoke/src/README.md",
"repo_id": "overleaf",
"token_count": 409
} | 556 |
const sinon = require('sinon')
const { expect } = require('chai')
const modulePath =
'../../../../app/src/Features/Authentication/SessionManager.js'
const SandboxedModule = require('sandboxed-module')
const tk = require('timekeeper')
const { ObjectId } = require('mongodb')
describe('SessionManager', function () {
beforeEach(function () {
this.UserModel = { findOne: sinon.stub() }
this.SessionManager = SandboxedModule.require(modulePath, {
requires: {},
})
this.user = {
_id: ObjectId(),
email: (this.email = 'USER@example.com'),
first_name: 'bob',
last_name: 'brown',
referal_id: 1234,
isAdmin: false,
}
this.session = sinon.stub()
})
afterEach(function () {
tk.reset()
})
describe('isUserLoggedIn', function () {
beforeEach(function () {
this.stub = sinon.stub(this.SessionManager, 'getLoggedInUserId')
})
afterEach(function () {
this.stub.restore()
})
it('should do the right thing in all cases', function () {
this.SessionManager.getLoggedInUserId.returns('some_id')
expect(this.SessionManager.isUserLoggedIn(this.session)).to.equal(true)
this.SessionManager.getLoggedInUserId.returns(null)
expect(this.SessionManager.isUserLoggedIn(this.session)).to.equal(false)
this.SessionManager.getLoggedInUserId.returns(false)
expect(this.SessionManager.isUserLoggedIn(this.session)).to.equal(false)
this.SessionManager.getLoggedInUserId.returns(undefined)
expect(this.SessionManager.isUserLoggedIn(this.session)).to.equal(false)
})
})
describe('setInSessionUser', function () {
beforeEach(function () {
this.user = {
_id: 'id',
first_name: 'a',
last_name: 'b',
email: 'c',
}
this.SessionManager.getSessionUser = sinon.stub().returns(this.user)
})
it('should update the right properties', function () {
this.SessionManager.setInSessionUser(this.session, {
first_name: 'new_first_name',
email: 'new_email',
})
const expectedUser = {
_id: 'id',
first_name: 'new_first_name',
last_name: 'b',
email: 'new_email',
}
expect(this.user).to.deep.equal(expectedUser)
expect(this.user).to.deep.equal(expectedUser)
})
})
describe('getLoggedInUserId', function () {
beforeEach(function () {
this.req = { session: {} }
})
it('should return the user id from the session', function () {
this.user_id = '2134'
this.session.user = { _id: this.user_id }
const result = this.SessionManager.getLoggedInUserId(this.session)
expect(result).to.equal(this.user_id)
})
it('should return user for passport session', function () {
this.user_id = '2134'
this.session = {
passport: {
user: {
_id: this.user_id,
},
},
}
const result = this.SessionManager.getLoggedInUserId(this.session)
expect(result).to.equal(this.user_id)
})
it('should return null if there is no user on the session', function () {
this.session = {}
const result = this.SessionManager.getLoggedInUserId(this.session)
expect(result).to.equal(null)
})
it('should return null if there is no session', function () {
const result = this.SessionManager.getLoggedInUserId(undefined)
expect(result).to.equal(null)
})
})
})
| overleaf/web/test/unit/src/Authentication/SessionManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Authentication/SessionManagerTests.js",
"repo_id": "overleaf",
"token_count": 1417
} | 557 |
const sinon = require('sinon')
const { expect } = require('chai')
const modulePath = '../../../../app/src/Features/Compile/ClsiManager.js'
const SandboxedModule = require('sandboxed-module')
describe('ClsiManager', function () {
beforeEach(function () {
this.jar = { cookie: 'stuff' }
this.ClsiCookieManager = {
clearServerId: sinon.stub().yields(),
getCookieJar: sinon.stub().callsArgWith(1, null, this.jar),
setServerId: sinon.stub().callsArgWith(2),
_getServerId: sinon.stub(),
}
this.ClsiStateManager = {
computeHash: sinon.stub().callsArgWith(2, null, '01234567890abcdef'),
}
this.ClsiFormatChecker = {
checkRecoursesForProblems: sinon.stub().callsArgWith(1),
}
this.Project = {}
this.ProjectEntityHandler = {}
this.ProjectGetter = {}
this.DocumentUpdaterHandler = {
getProjectDocsIfMatch: sinon.stub().callsArgWith(2, null, null),
}
this.request = sinon.stub()
this.Metrics = {
Timer: class Metrics {
constructor() {
this.done = sinon.stub()
}
},
inc: sinon.stub(),
}
this.ClsiManager = SandboxedModule.require(modulePath, {
requires: {
'@overleaf/settings': (this.settings = {
apis: {
filestore: {
url: 'filestore.example.com',
secret: 'secret',
},
clsi: {
url: 'http://clsi.example.com',
},
clsi_priority: {
url: 'https://clsipremium.example.com',
},
},
}),
'../../models/Project': {
Project: this.Project,
},
'../Project/ProjectEntityHandler': this.ProjectEntityHandler,
'../Project/ProjectGetter': this.ProjectGetter,
'../DocumentUpdater/DocumentUpdaterHandler': this
.DocumentUpdaterHandler,
'./ClsiCookieManager': () => this.ClsiCookieManager,
'./ClsiStateManager': this.ClsiStateManager,
request: this.request,
'./ClsiFormatChecker': this.ClsiFormatChecker,
'@overleaf/metrics': this.Metrics,
},
})
this.project_id = 'project-id'
this.user_id = 'user-id'
this.callback = sinon.stub()
})
describe('sendRequest', function () {
beforeEach(function () {
this.ClsiManager._buildRequest = sinon
.stub()
.callsArgWith(2, null, (this.request = 'mock-request'))
this.ClsiCookieManager._getServerId.callsArgWith(1, null, 'clsi3')
})
describe('with a successful compile', function () {
beforeEach(function () {
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'success'),
outputFiles: [
{
url: `${this.settings.apis.clsi.url}/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.pdf`,
path: 'output.pdf',
type: 'pdf',
build: 1234,
},
{
url: `${this.settings.apis.clsi.url}/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.log`,
path: 'output.log',
type: 'log',
build: 1234,
},
],
},
})
this.ClsiManager.sendRequest(
this.project_id,
this.user_id,
{ compileGroup: 'standard' },
this.callback
)
})
it('should build the request', function () {
this.ClsiManager._buildRequest
.calledWith(this.project_id)
.should.equal(true)
})
it('should send the request to the CLSI', function () {
this.ClsiManager._postToClsi
.calledWith(this.project_id, this.user_id, this.request, 'standard')
.should.equal(true)
})
it('should call the callback with the status and output files', function () {
const outputFiles = [
{
url: `/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.pdf`,
path: 'output.pdf',
type: 'pdf',
build: 1234,
// gets dropped by JSON.stringify
contentId: undefined,
ranges: undefined,
size: undefined,
},
{
url: `/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.log`,
path: 'output.log',
type: 'log',
build: 1234,
// gets dropped by JSON.stringify
contentId: undefined,
ranges: undefined,
size: undefined,
},
]
this.callback
.calledWith(null, this.status, outputFiles)
.should.equal(true)
})
})
describe('with ranges on the pdf and stats/timings details', function () {
beforeEach(function () {
this.ClsiManager._postToClsi = sinon.stub().yields(
null,
{
compile: {
status: 'success',
stats: { fooStat: 1 },
timings: { barTiming: 2 },
outputFiles: [
{
url: `${this.settings.apis.clsi.url}/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.pdf`,
path: 'output.pdf',
type: 'pdf',
build: 1234,
contentId: '123-321',
ranges: [{ start: 1, end: 42, hash: 'foo' }],
size: 42,
},
{
url: `${this.settings.apis.clsi.url}/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.log`,
path: 'output.log',
type: 'log',
build: 1234,
},
],
},
},
'clsi-server-id-43'
)
this.ClsiCookieManager._getServerId.yields(null, 'clsi-server-id-42')
this.ClsiManager.sendRequest(
this.project_id,
this.user_id,
{ compileGroup: 'standard' },
this.callback
)
})
it('should emit the caching details and stats/timings', function () {
const outputFiles = [
{
url: `/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.pdf`,
path: 'output.pdf',
type: 'pdf',
build: 1234,
contentId: '123-321',
ranges: [{ start: 1, end: 42, hash: 'foo' }],
size: 42,
},
{
url: `/project/${this.project_id}/user/${this.user_id}/build/1234/output/output.log`,
path: 'output.log',
type: 'log',
build: 1234,
// gets dropped by JSON.stringify
contentId: undefined,
ranges: undefined,
size: undefined,
},
]
const validationError = undefined
expect(this.callback).to.have.been.calledWith(
null,
'success',
outputFiles,
'clsi-server-id-43',
validationError,
{ fooStat: 1 },
{ barTiming: 2 }
)
})
})
describe('with a failed compile', function () {
beforeEach(function () {
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'failure'),
},
})
this.ClsiManager.sendRequest(
this.project_id,
this.user_id,
{},
this.callback
)
})
it('should call the callback with a failure status', function () {
this.callback.calledWith(null, this.status).should.equal(true)
})
})
describe('with a sync conflict', function () {
beforeEach(function () {
this.ClsiManager.sendRequestOnce = sinon.stub()
this.ClsiManager.sendRequestOnce
.withArgs(this.project_id, this.user_id, { syncType: 'full' })
.callsArgWith(3, null, (this.status = 'success'))
this.ClsiManager.sendRequestOnce
.withArgs(this.project_id, this.user_id, {})
.callsArgWith(3, null, 'conflict')
this.ClsiManager.sendRequest(
this.project_id,
this.user_id,
{},
this.callback
)
})
it('should call the sendRequestOnce method twice', function () {
this.ClsiManager.sendRequestOnce.calledTwice.should.equal(true)
})
it('should call the sendRequestOnce method with syncType:full', function () {
this.ClsiManager.sendRequestOnce
.calledWith(this.project_id, this.user_id, { syncType: 'full' })
.should.equal(true)
})
it('should call the sendRequestOnce method without syncType:full', function () {
this.ClsiManager.sendRequestOnce
.calledWith(this.project_id, this.user_id, {})
.should.equal(true)
})
it('should call the callback with a success status', function () {
this.callback.calledWith(null, this.status).should.equal(true)
})
})
describe('with an unavailable response', function () {
beforeEach(function () {
this.ClsiManager.sendRequestOnce = sinon.stub()
this.ClsiManager.sendRequestOnce
.withArgs(this.project_id, this.user_id, {
syncType: 'full',
forceNewClsiServer: true,
})
.callsArgWith(3, null, (this.status = 'success'))
this.ClsiManager.sendRequestOnce
.withArgs(this.project_id, this.user_id, {})
.callsArgWith(3, null, 'unavailable')
this.ClsiManager.sendRequest(
this.project_id,
this.user_id,
{},
this.callback
)
})
it('should call the sendRequestOnce method twice', function () {
this.ClsiManager.sendRequestOnce.calledTwice.should.equal(true)
})
it('should call the sendRequestOnce method with forceNewClsiServer:true', function () {
this.ClsiManager.sendRequestOnce
.calledWith(this.project_id, this.user_id, {
forceNewClsiServer: true,
syncType: 'full',
})
.should.equal(true)
})
it('should call the sendRequestOnce method without forceNewClsiServer:true', function () {
this.ClsiManager.sendRequestOnce
.calledWith(this.project_id, this.user_id, {})
.should.equal(true)
})
it('should call the callback with a success status', function () {
this.callback.calledWith(null, this.status).should.equal(true)
})
})
describe('when the resources fail the precompile check', function () {
beforeEach(function () {
this.ClsiFormatChecker.checkRecoursesForProblems = sinon
.stub()
.callsArgWith(1, new Error('failed'))
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'failure'),
},
})
this.ClsiManager.sendRequest(
this.project_id,
this.user_id,
{},
this.callback
)
})
it('should call the callback only once', function () {
this.callback.calledOnce.should.equal(true)
})
it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(sinon.match.instanceOf(Error))
})
})
})
describe('sendExternalRequest', function () {
beforeEach(function () {
this.submission_id = 'submission-id'
this.clsi_request = 'mock-request'
this.ClsiCookieManager._getServerId.callsArgWith(1, null, 'clsi3')
})
describe('with a successful compile', function () {
beforeEach(function () {
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'success'),
outputFiles: [
{
url: `${this.settings.apis.clsi.url}/project/${this.submission_id}/build/1234/output/output.pdf`,
path: 'output.pdf',
type: 'pdf',
build: 1234,
},
{
url: `${this.settings.apis.clsi.url}/project/${this.submission_id}/build/1234/output/output.log`,
path: 'output.log',
type: 'log',
build: 1234,
},
],
},
})
this.ClsiManager.sendExternalRequest(
this.submission_id,
this.clsi_request,
{ compileGroup: 'standard' },
this.callback
)
})
it('should send the request to the CLSI', function () {
this.ClsiManager._postToClsi
.calledWith(this.submission_id, null, this.clsi_request, 'standard')
.should.equal(true)
})
it('should call the callback with the status and output files', function () {
const outputFiles = [
{
url: `/project/${this.submission_id}/build/1234/output/output.pdf`,
path: 'output.pdf',
type: 'pdf',
build: 1234,
// gets dropped by JSON.stringify
contentId: undefined,
ranges: undefined,
size: undefined,
},
{
url: `/project/${this.submission_id}/build/1234/output/output.log`,
path: 'output.log',
type: 'log',
build: 1234,
// gets dropped by JSON.stringify
contentId: undefined,
ranges: undefined,
size: undefined,
},
]
this.callback
.calledWith(null, this.status, outputFiles)
.should.equal(true)
})
})
describe('with a failed compile', function () {
beforeEach(function () {
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'failure'),
},
})
this.ClsiManager.sendExternalRequest(
this.submission_id,
this.clsi_request,
{},
this.callback
)
})
it('should call the callback with a failure status', function () {
this.callback.calledWith(null, this.status).should.equal(true)
})
})
describe('when the resources fail the precompile check', function () {
beforeEach(function () {
this.ClsiFormatChecker.checkRecoursesForProblems = sinon
.stub()
.callsArgWith(1, new Error('failed'))
this.ClsiManager._postToClsi = sinon.stub().callsArgWith(4, null, {
compile: {
status: (this.status = 'failure'),
},
})
this.ClsiManager.sendExternalRequest(
this.submission_id,
this.clsi_request,
{},
this.callback
)
})
it('should call the callback only once', function () {
this.callback.calledOnce.should.equal(true)
})
it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(sinon.match.instanceOf(Error))
})
})
})
describe('deleteAuxFiles', function () {
beforeEach(function () {
this.ClsiManager._makeRequestWithClsiServerId = sinon.stub().yields(null)
this.DocumentUpdaterHandler.clearProjectState = sinon.stub().callsArg(1)
})
describe('with the standard compileGroup', function () {
beforeEach(function () {
this.ClsiManager.deleteAuxFiles(
this.project_id,
this.user_id,
{ compileGroup: 'standard' },
'node-1',
this.callback
)
})
it('should call the delete method in the standard CLSI', function () {
this.ClsiManager._makeRequestWithClsiServerId
.calledWith(
this.project_id,
{
method: 'DELETE',
url: `${this.settings.apis.clsi.url}/project/${this.project_id}/user/${this.user_id}`,
},
'node-1'
)
.should.equal(true)
})
it('should clear the project state from the docupdater', function () {
this.DocumentUpdaterHandler.clearProjectState
.calledWith(this.project_id)
.should.equal(true)
})
it('should clear the clsi persistance', function () {
this.ClsiCookieManager.clearServerId
.calledWith(this.project_id)
.should.equal(true)
})
it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
})
describe('_buildRequest', function () {
beforeEach(function () {
this.project = {
_id: this.project_id,
compiler: (this.compiler = 'latex'),
rootDoc_id: 'mock-doc-id-1',
imageName: (this.image = 'mock-image-name'),
}
this.docs = {
'/main.tex': (this.doc_1 = {
name: 'main.tex',
_id: 'mock-doc-id-1',
lines: ['Hello', 'world'],
}),
'/chapters/chapter1.tex': (this.doc_2 = {
name: 'chapter1.tex',
_id: 'mock-doc-id-2',
lines: ['Chapter 1'],
}),
}
this.files = {
'/images/image.png': (this.file_1 = {
name: 'image.png',
_id: 'mock-file-id-1',
created: new Date(),
}),
}
this.Project.findById = sinon.stub().callsArgWith(2, null, this.project)
this.ProjectEntityHandler.getAllDocs = sinon
.stub()
.callsArgWith(1, null, this.docs)
this.ProjectEntityHandler.getAllFiles = sinon
.stub()
.callsArgWith(1, null, this.files)
this.ProjectGetter.getProject = sinon
.stub()
.callsArgWith(2, null, this.project)
this.DocumentUpdaterHandler.flushProjectToMongo = sinon
.stub()
.callsArgWith(1, null)
})
describe('with a valid project', function () {
beforeEach(function (done) {
this.ClsiManager._buildRequest(
this.project_id,
{ timeout: 100, compileGroup: 'standard' },
(err, request) => {
if (err != null) {
return done(err)
}
this.request = request
done()
}
)
})
it('should get the project with the required fields', function () {
this.ProjectGetter.getProject
.calledWith(this.project_id, {
compiler: 1,
rootDoc_id: 1,
imageName: 1,
rootFolder: 1,
})
.should.equal(true)
})
it('should flush the project to the database', function () {
this.DocumentUpdaterHandler.flushProjectToMongo
.calledWith(this.project_id)
.should.equal(true)
})
it('should get all the docs', function () {
this.ProjectEntityHandler.getAllDocs
.calledWith(this.project_id)
.should.equal(true)
})
it('should get all the files', function () {
this.ProjectEntityHandler.getAllFiles
.calledWith(this.project_id)
.should.equal(true)
})
it('should build up the CLSI request', function () {
expect(this.request).to.deep.equal({
compile: {
options: {
compiler: this.compiler,
timeout: 100,
imageName: this.image,
draft: false,
check: undefined,
syncType: undefined, // "full"
syncState: undefined,
compileGroup: 'standard',
enablePdfCaching: false,
}, // "01234567890abcdef"
rootResourcePath: 'main.tex',
resources: [
{
path: 'main.tex',
content: this.doc_1.lines.join('\n'),
},
{
path: 'chapters/chapter1.tex',
content: this.doc_2.lines.join('\n'),
},
{
path: 'images/image.png',
url: `${this.settings.apis.filestore.url}/project/${this.project_id}/file/${this.file_1._id}`,
modified: this.file_1.created.getTime(),
},
],
},
})
})
})
describe('with the incremental compile option', function () {
beforeEach(function (done) {
this.ClsiStateManager.computeHash = sinon
.stub()
.callsArgWith(
2,
null,
(this.project_state_hash = '01234567890abcdef')
)
this.DocumentUpdaterHandler.getProjectDocsIfMatch = sinon
.stub()
.callsArgWith(2, null, [
{ _id: this.doc_1._id, lines: this.doc_1.lines, v: 123 },
])
this.ProjectEntityHandler.getAllDocPathsFromProject = sinon
.stub()
.callsArgWith(1, null, { 'mock-doc-id-1': 'main.tex' })
this.ClsiManager._buildRequest(
this.project_id,
{
timeout: 100,
incrementalCompilesEnabled: true,
compileGroup: 'priority',
},
(err, request) => {
if (err != null) {
return done(err)
}
this.request = request
done()
}
)
})
it('should get the project with the required fields', function () {
this.ProjectGetter.getProject
.calledWith(this.project_id, {
compiler: 1,
rootDoc_id: 1,
imageName: 1,
rootFolder: 1,
})
.should.equal(true)
})
it('should not explicitly flush the project to the database', function () {
this.DocumentUpdaterHandler.flushProjectToMongo
.calledWith(this.project_id)
.should.equal(false)
})
it('should get only the live docs from the docupdater with a background flush in docupdater', function () {
this.DocumentUpdaterHandler.getProjectDocsIfMatch
.calledWith(this.project_id)
.should.equal(true)
})
it('should not get any of the files', function () {
this.ProjectEntityHandler.getAllFiles.called.should.equal(false)
})
it('should build up the CLSI request', function () {
expect(this.request).to.deep.equal({
compile: {
options: {
compiler: this.compiler,
timeout: 100,
imageName: this.image,
draft: false,
check: undefined,
syncType: 'incremental',
syncState: '01234567890abcdef',
compileGroup: 'priority',
enablePdfCaching: false,
},
rootResourcePath: 'main.tex',
resources: [
{
path: 'main.tex',
content: this.doc_1.lines.join('\n'),
},
],
},
})
})
describe('when the root doc is set and not in the docupdater', function () {
beforeEach(function (done) {
this.ClsiStateManager.computeHash = sinon
.stub()
.callsArgWith(
2,
null,
(this.project_state_hash = '01234567890abcdef')
)
this.DocumentUpdaterHandler.getProjectDocsIfMatch = sinon
.stub()
.callsArgWith(2, null, [
{ _id: this.doc_1._id, lines: this.doc_1.lines, v: 123 },
])
this.ProjectEntityHandler.getAllDocPathsFromProject = sinon
.stub()
.callsArgWith(1, null, {
'mock-doc-id-1': 'main.tex',
'mock-doc-id-2': '/chapters/chapter1.tex',
})
this.ClsiManager._buildRequest(
this.project_id,
{
timeout: 100,
incrementalCompilesEnabled: true,
rootDoc_id: 'mock-doc-id-2',
},
(err, request) => {
if (err != null) {
return done(err)
}
this.request = request
done()
}
)
})
it('should still change the root path', function () {
this.request.compile.rootResourcePath.should.equal(
'chapters/chapter1.tex'
)
})
})
})
describe('when root doc override is valid', function () {
beforeEach(function (done) {
this.ClsiManager._buildRequest(
this.project_id,
{ rootDoc_id: 'mock-doc-id-2' },
(err, request) => {
if (err != null) {
return done(err)
}
this.request = request
done()
}
)
})
it('should change root path', function () {
this.request.compile.rootResourcePath.should.equal(
'chapters/chapter1.tex'
)
})
})
describe('when root doc override is invalid', function () {
beforeEach(function (done) {
this.ClsiManager._buildRequest(
this.project_id,
{ rootDoc_id: 'invalid-id' },
(err, request) => {
if (err != null) {
return done(err)
}
this.request = request
done()
}
)
})
it('should fallback to default root doc', function () {
this.request.compile.rootResourcePath.should.equal('main.tex')
})
})
describe('when the project has an invalid compiler', function () {
beforeEach(function (done) {
this.project.compiler = 'context'
this.ClsiManager._buildRequest(this.project, null, (err, request) => {
if (err != null) {
return done(err)
}
this.request = request
done()
})
})
it('should set the compiler to pdflatex', function () {
this.request.compile.options.compiler.should.equal('pdflatex')
})
})
describe('when there is no valid root document', function () {
beforeEach(function (done) {
this.project.rootDoc_id = 'not-valid'
this.ClsiManager._buildRequest(this.project, null, (error, request) => {
this.error = error
this.request = request
done()
})
})
it('should set to main.tex', function () {
this.request.compile.rootResourcePath.should.equal('main.tex')
})
})
describe('when there is no valid root document and no main.tex document', function () {
beforeEach(function () {
this.project.rootDoc_id = 'not-valid'
this.docs = {
'/other.tex': (this.doc_1 = {
name: 'other.tex',
_id: 'mock-doc-id-1',
lines: ['Hello', 'world'],
}),
'/chapters/chapter1.tex': (this.doc_2 = {
name: 'chapter1.tex',
_id: 'mock-doc-id-2',
lines: ['Chapter 1'],
}),
}
this.ProjectEntityHandler.getAllDocs = sinon
.stub()
.callsArgWith(1, null, this.docs)
this.ClsiManager._buildRequest(this.project, null, this.callback)
})
it('should report an error', function () {
this.callback.should.have.been.calledWith(sinon.match.instanceOf(Error))
})
})
describe('when there is no valid root document and a single document which is not main.tex', function () {
beforeEach(function (done) {
this.project.rootDoc_id = 'not-valid'
this.docs = {
'/other.tex': (this.doc_1 = {
name: 'other.tex',
_id: 'mock-doc-id-1',
lines: ['Hello', 'world'],
}),
}
this.ProjectEntityHandler.getAllDocs = sinon
.stub()
.callsArgWith(1, null, this.docs)
this.ClsiManager._buildRequest(this.project, null, (error, request) => {
this.error = error
this.request = request
done()
})
})
it('should set io to the only file', function () {
this.request.compile.rootResourcePath.should.equal('other.tex')
})
})
describe('with the draft option', function () {
it('should add the draft option into the request', function (done) {
this.ClsiManager._buildRequest(
this.project_id,
{ timeout: 100, draft: true },
(err, request) => {
if (err != null) {
return done(err)
}
request.compile.options.draft.should.equal(true)
done()
}
)
})
})
})
describe('_postToClsi', function () {
beforeEach(function () {
this.req = { mock: 'req', compile: {} }
})
describe('successfully', function () {
beforeEach(function () {
this.ClsiManager._makeRequest = sinon
.stub()
.callsArgWith(
2,
null,
{ statusCode: 204 },
(this.body = { mock: 'foo' })
)
this.ClsiManager._postToClsi(
this.project_id,
this.user_id,
this.req,
'standard',
this.callback
)
})
it('should send the request to the CLSI', function () {
const url = `${this.settings.apis.clsi.url}/project/${this.project_id}/user/${this.user_id}/compile`
this.ClsiManager._makeRequest
.calledWith(this.project_id, {
method: 'POST',
url,
json: this.req,
})
.should.equal(true)
})
it('should call the callback with the body and no error', function () {
this.callback.calledWith(null, this.body).should.equal(true)
})
})
describe('when the CLSI returns an error', function () {
beforeEach(function () {
this.ClsiManager._makeRequest = sinon
.stub()
.callsArgWith(
2,
null,
{ statusCode: 500 },
(this.body = { mock: 'foo' })
)
this.ClsiManager._postToClsi(
this.project_id,
this.user_id,
this.req,
'standard',
this.callback
)
})
it('should call the callback with an error', function () {
this.callback.should.have.been.calledWith(sinon.match.instanceOf(Error))
})
})
})
describe('wordCount', function () {
beforeEach(function () {
this.ClsiManager._makeRequestWithClsiServerId = sinon
.stub()
.yields(null, { statusCode: 200 }, (this.body = { mock: 'foo' }))
this.ClsiManager._buildRequest = sinon.stub().callsArgWith(
2,
null,
(this.req = {
compile: { rootResourcePath: 'rootfile.text', options: {} },
})
)
})
describe('with root file', function () {
beforeEach(function () {
this.ClsiManager.wordCount(
this.project_id,
this.user_id,
false,
{},
'node-1',
this.callback
)
})
it('should call wordCount with root file', function () {
this.ClsiManager._makeRequestWithClsiServerId
.calledWith(
this.project_id,
{
method: 'GET',
url: `http://clsi.example.com/project/${this.project_id}/user/${this.user_id}/wordcount`,
qs: {
file: 'rootfile.text',
image: undefined,
},
},
'node-1'
)
.should.equal(true)
})
it('should call the callback', function () {
this.callback.called.should.equal(true)
})
})
describe('with param file', function () {
beforeEach(function () {
this.ClsiManager.wordCount(
this.project_id,
this.user_id,
'main.tex',
{},
'node-2',
this.callback
)
})
it('should call wordCount with param file', function () {
this.ClsiManager._makeRequestWithClsiServerId
.calledWith(
this.project_id,
{
method: 'GET',
url: `http://clsi.example.com/project/${this.project_id}/user/${this.user_id}/wordcount`,
qs: { file: 'main.tex', image: undefined },
},
'node-2'
)
.should.equal(true)
})
})
describe('with image', function () {
beforeEach(function () {
this.req.compile.options.imageName = this.image =
'example.com/mock/image'
this.ClsiManager.wordCount(
this.project_id,
this.user_id,
'main.tex',
{},
'node-3',
this.callback
)
})
it('should call wordCount with file and image', function () {
this.ClsiManager._makeRequestWithClsiServerId
.calledWith(
this.project_id,
{
method: 'GET',
url: `http://clsi.example.com/project/${this.project_id}/user/${this.user_id}/wordcount`,
qs: { file: 'main.tex', image: this.image },
},
'node-3'
)
.should.equal(true)
})
})
})
describe('_makeRequest', function () {
beforeEach(function () {
this.response = { there: 'something' }
this.request.callsArgWith(1, null, this.response)
this.opts = {
method: 'SOMETHIGN',
url: 'http://a place on the web',
}
})
it('should process a request with a cookie jar', function (done) {
this.ClsiManager._makeRequest(this.project_id, this.opts, () => {
const args = this.request.args[0]
args[0].method.should.equal(this.opts.method)
args[0].url.should.equal(this.opts.url)
args[0].jar.should.equal(this.jar)
done()
})
})
it('should set the cookie again on response as it might have changed', function (done) {
this.ClsiManager._makeRequest(this.project_id, this.opts, () => {
this.ClsiCookieManager.setServerId
.calledWith(this.project_id, this.response)
.should.equal(true)
done()
})
})
})
describe('_makeRequestWithClsiServerId', function () {
beforeEach(function () {
this.response = { statusCode: 200 }
this.request.yields(null, this.response)
this.opts = {
method: 'GET',
url: 'http://clsi',
}
})
describe('with a regular request', function () {
it('should process a request with a cookie jar', function (done) {
this.ClsiManager._makeRequestWithClsiServerId(
this.project_id,
this.opts,
undefined,
err => {
if (err) return done(err)
const args = this.request.args[0]
args[0].method.should.equal(this.opts.method)
args[0].url.should.equal(this.opts.url)
args[0].jar.should.equal(this.jar)
expect(args[0].qs).to.not.exist
done()
}
)
})
it('should persist the cookie from the response', function (done) {
this.ClsiManager._makeRequestWithClsiServerId(
this.project_id,
this.opts,
undefined,
err => {
if (err) return done(err)
this.ClsiCookieManager.setServerId
.calledWith(this.project_id, this.response)
.should.equal(true)
done()
}
)
})
})
describe('with a persistent request', function () {
it('should not add a cookie jar', function (done) {
this.ClsiManager._makeRequestWithClsiServerId(
this.project_id,
this.opts,
'node-1',
err => {
if (err) return done(err)
const requestOpts = this.request.args[0][0]
expect(requestOpts.method).to.equal(this.opts.method)
expect(requestOpts.url).to.equal(this.opts.url)
expect(requestOpts.jar).to.not.exist
expect(requestOpts.qs).to.deep.equal({ clsiserverid: 'node-1' })
done()
}
)
})
it('should not persist a cookie on response', function (done) {
this.ClsiManager._makeRequestWithClsiServerId(
this.project_id,
this.opts,
'node-1',
err => {
if (err) return done(err)
expect(this.ClsiCookieManager.setServerId.called).to.equal(false)
done()
}
)
})
})
})
describe('_makeGoogleCloudRequest', function () {
beforeEach(function () {
this.settings.apis.clsi_new = { url: 'https://compiles.somewhere.test' }
this.response = { there: 'something' }
this.request.callsArgWith(1, null, this.response)
this.opts = {
url: this.ClsiManager._getCompilerUrl(null, this.project_id),
}
})
it('should change the domain on the url', function (done) {
this.ClsiManager._makeNewBackendRequest(
this.project_id,
this.opts,
() => {
const args = this.request.args[0]
args[0].url.should.equal(
`https://compiles.somewhere.test/project/${this.project_id}`
)
done()
}
)
})
it('should not make a request if there is not clsi_new url', function (done) {
this.settings.apis.clsi_new = undefined
this.ClsiManager._makeNewBackendRequest(
this.project_id,
this.opts,
err => {
expect(err).to.equal(undefined)
this.request.callCount.should.equal(0)
done()
}
)
})
})
})
| overleaf/web/test/unit/src/Compile/ClsiManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Compile/ClsiManagerTests.js",
"repo_id": "overleaf",
"token_count": 18997
} | 558 |
/* eslint-disable
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS101: Remove unnecessary use of Array.from
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const sinon = require('sinon')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Editor/EditorRealTimeController'
)
describe('EditorRealTimeController', function () {
beforeEach(function () {
this.rclient = { publish: sinon.stub() }
this.Metrics = { summary: sinon.stub() }
this.EditorRealTimeController = SandboxedModule.require(modulePath, {
requires: {
'../../infrastructure/RedisWrapper': {
client: () => this.rclient,
},
'../../infrastructure/Server': {
io: (this.io = {}),
},
'@overleaf/settings': { redis: {} },
'@overleaf/metrics': this.Metrics,
crypto: (this.crypto = {
randomBytes: sinon
.stub()
.withArgs(4)
.returns(Buffer.from([0x1, 0x2, 0x3, 0x4])),
}),
os: (this.os = { hostname: sinon.stub().returns('somehost') }),
},
})
this.room_id = 'room-id'
this.message = 'message-to-editor'
return (this.payload = ['argument one', 42])
})
describe('emitToRoom', function () {
beforeEach(function () {
this.message_id = 'web:somehost:01020304-0'
return this.EditorRealTimeController.emitToRoom(
this.room_id,
this.message,
...Array.from(this.payload)
)
})
it('should publish the message to redis', function () {
return this.rclient.publish
.calledWith(
'editor-events',
JSON.stringify({
room_id: this.room_id,
message: this.message,
payload: this.payload,
_id: this.message_id,
})
)
.should.equal(true)
})
it('should track the payload size', function () {
this.Metrics.summary
.calledWith(
'redis.publish.editor-events',
JSON.stringify({
room_id: this.room_id,
message: this.message,
payload: this.payload,
_id: this.message_id,
}).length
)
.should.equal(true)
})
})
describe('emitToAll', function () {
beforeEach(function () {
this.EditorRealTimeController.emitToRoom = sinon.stub()
return this.EditorRealTimeController.emitToAll(
this.message,
...Array.from(this.payload)
)
})
it("should emit to the room 'all'", function () {
return this.EditorRealTimeController.emitToRoom
.calledWith('all', this.message, ...Array.from(this.payload))
.should.equal(true)
})
})
})
| overleaf/web/test/unit/src/Editor/EditorRealTimeControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Editor/EditorRealTimeControllerTests.js",
"repo_id": "overleaf",
"token_count": 1330
} | 559 |
/* eslint-disable
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sinon = require('sinon')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const modulePath = '../../../../app/src/Features/History/HistoryController'
const SandboxedModule = require('sandboxed-module')
describe('HistoryController', function () {
beforeEach(function () {
this.callback = sinon.stub()
this.user_id = 'user-id-123'
this.SessionManager = {
getLoggedInUserId: sinon.stub().returns(this.user_id),
}
this.HistoryController = SandboxedModule.require(modulePath, {
requires: {
request: (this.request = sinon.stub()),
'@overleaf/settings': (this.settings = {}),
'../Authentication/SessionManager': this.SessionManager,
'./HistoryManager': (this.HistoryManager = {}),
'../Project/ProjectDetailsHandler': (this.ProjectDetailsHandler = {}),
'../Project/ProjectEntityUpdateHandler': (this.ProjectEntityUpdateHandler = {}),
'../User/UserGetter': (this.UserGetter = {}),
'./RestoreManager': (this.RestoreManager = {}),
},
})
return (this.settings.apis = {
trackchanges: {
enabled: false,
url: 'http://trackchanges.example.com',
},
project_history: {
url: 'http://project_history.example.com',
},
})
})
describe('selectHistoryApi', function () {
beforeEach(function () {
this.req = { url: '/mock/url', method: 'POST', params: {} }
this.res = 'mock-res'
return (this.next = sinon.stub())
})
describe('for a project with project history', function () {
beforeEach(function () {
this.ProjectDetailsHandler.getDetails = sinon
.stub()
.callsArgWith(1, null, {
overleaf: { history: { id: 42, display: true } },
})
return this.HistoryController.selectHistoryApi(
this.req,
this.res,
this.next
)
})
it('should set the flag for project history to true', function () {
return this.req.useProjectHistory.should.equal(true)
})
})
describe('for any other project ', function () {
beforeEach(function () {
this.ProjectDetailsHandler.getDetails = sinon
.stub()
.callsArgWith(1, null, {})
return this.HistoryController.selectHistoryApi(
this.req,
this.res,
this.next
)
})
it('should not set the flag for project history to false', function () {
return this.req.useProjectHistory.should.equal(false)
})
})
})
describe('proxyToHistoryApi', function () {
beforeEach(function () {
this.req = { url: '/mock/url', method: 'POST' }
this.res = 'mock-res'
this.next = sinon.stub()
this.proxy = {
events: {},
pipe: sinon.stub(),
on(event, handler) {
return (this.events[event] = handler)
},
}
return this.request.returns(this.proxy)
})
describe('for a project with the project history flag', function () {
beforeEach(function () {
this.req.useProjectHistory = true
return this.HistoryController.proxyToHistoryApi(
this.req,
this.res,
this.next
)
})
it('should get the user id', function () {
return this.SessionManager.getLoggedInUserId
.calledWith(this.req.session)
.should.equal(true)
})
it('should call the project history api', function () {
return this.request
.calledWith({
url: `${this.settings.apis.project_history.url}${this.req.url}`,
method: this.req.method,
headers: {
'X-User-Id': this.user_id,
},
})
.should.equal(true)
})
it('should pipe the response to the client', function () {
return this.proxy.pipe.calledWith(this.res).should.equal(true)
})
})
describe('for a project without the project history flag', function () {
beforeEach(function () {
this.req.useProjectHistory = false
return this.HistoryController.proxyToHistoryApi(
this.req,
this.res,
this.next
)
})
it('should get the user id', function () {
return this.SessionManager.getLoggedInUserId
.calledWith(this.req.session)
.should.equal(true)
})
it('should call the track changes api', function () {
return this.request
.calledWith({
url: `${this.settings.apis.trackchanges.url}${this.req.url}`,
method: this.req.method,
headers: {
'X-User-Id': this.user_id,
},
})
.should.equal(true)
})
it('should pipe the response to the client', function () {
return this.proxy.pipe.calledWith(this.res).should.equal(true)
})
})
describe('with an error', function () {
beforeEach(function () {
this.HistoryController.proxyToHistoryApi(this.req, this.res, this.next)
return this.proxy.events.error.call(
this.proxy,
(this.error = new Error('oops'))
)
})
it('should pass the error up the call chain', function () {
return this.next.calledWith(this.error).should.equal(true)
})
})
})
describe('proxyToHistoryApiAndInjectUserDetails', function () {
beforeEach(function () {
this.req = { url: '/mock/url', method: 'POST' }
this.res = { json: sinon.stub() }
this.next = sinon.stub()
this.request.yields(null, { statusCode: 200 }, (this.data = 'mock-data'))
return (this.HistoryManager.injectUserDetails = sinon
.stub()
.yields(null, (this.data_with_users = 'mock-injected-data')))
})
describe('for a project with the project history flag', function () {
beforeEach(function () {
this.req.useProjectHistory = true
return this.HistoryController.proxyToHistoryApiAndInjectUserDetails(
this.req,
this.res,
this.next
)
})
it('should get the user id', function () {
return this.SessionManager.getLoggedInUserId
.calledWith(this.req.session)
.should.equal(true)
})
it('should call the project history api', function () {
return this.request
.calledWith({
url: `${this.settings.apis.project_history.url}${this.req.url}`,
method: this.req.method,
json: true,
headers: {
'X-User-Id': this.user_id,
},
})
.should.equal(true)
})
it('should inject the user data', function () {
return this.HistoryManager.injectUserDetails
.calledWith(this.data)
.should.equal(true)
})
it('should return the data with users to the client', function () {
return this.res.json.calledWith(this.data_with_users).should.equal(true)
})
})
describe('for a project without the project history flag', function () {
beforeEach(function () {
this.req.useProjectHistory = false
return this.HistoryController.proxyToHistoryApiAndInjectUserDetails(
this.req,
this.res,
this.next
)
})
it('should get the user id', function () {
return this.SessionManager.getLoggedInUserId
.calledWith(this.req.session)
.should.equal(true)
})
it('should call the track changes api', function () {
return this.request
.calledWith({
url: `${this.settings.apis.trackchanges.url}${this.req.url}`,
method: this.req.method,
json: true,
headers: {
'X-User-Id': this.user_id,
},
})
.should.equal(true)
})
it('should inject the user data', function () {
return this.HistoryManager.injectUserDetails
.calledWith(this.data)
.should.equal(true)
})
it('should return the data with users to the client', function () {
return this.res.json.calledWith(this.data_with_users).should.equal(true)
})
})
})
describe('proxyToHistoryApiAndInjectUserDetails (with the history API failing)', function () {
beforeEach(function () {
this.req = { url: '/mock/url', method: 'POST', useProjectHistory: true }
this.res = { json: sinon.stub() }
this.next = sinon.stub()
this.request.yields(null, { statusCode: 500 }, (this.data = 'mock-data'))
this.HistoryManager.injectUserDetails = sinon
.stub()
.yields(null, (this.data_with_users = 'mock-injected-data'))
return this.HistoryController.proxyToHistoryApiAndInjectUserDetails(
this.req,
this.res,
this.next
)
})
it('should not inject the user data', function () {
return this.HistoryManager.injectUserDetails
.calledWith(this.data)
.should.equal(false)
})
it('should not return the data with users to the client', function () {
return this.res.json.calledWith(this.data_with_users).should.equal(false)
})
})
describe('resyncProjectHistory', function () {
describe('for a project without project-history enabled', function () {
beforeEach(function () {
this.project_id = 'mock-project-id'
this.req = { params: { Project_id: this.project_id } }
this.res = { sendStatus: sinon.stub() }
this.next = sinon.stub()
this.error = new Errors.ProjectHistoryDisabledError()
this.ProjectEntityUpdateHandler.resyncProjectHistory = sinon
.stub()
.yields(this.error)
return this.HistoryController.resyncProjectHistory(
this.req,
this.res,
this.next
)
})
it('response with a 404', function () {
return this.res.sendStatus.calledWith(404).should.equal(true)
})
})
describe('for a project with project-history enabled', function () {
beforeEach(function () {
this.project_id = 'mock-project-id'
this.req = { params: { Project_id: this.project_id } }
this.res = { sendStatus: sinon.stub() }
this.next = sinon.stub()
this.ProjectEntityUpdateHandler.resyncProjectHistory = sinon
.stub()
.yields()
return this.HistoryController.resyncProjectHistory(
this.req,
this.res,
this.next
)
})
it('resyncs the project', function () {
return this.ProjectEntityUpdateHandler.resyncProjectHistory
.calledWith(this.project_id)
.should.equal(true)
})
it('responds with a 204', function () {
return this.res.sendStatus.calledWith(204).should.equal(true)
})
})
})
})
| overleaf/web/test/unit/src/History/HistoryControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/History/HistoryControllerTests.js",
"repo_id": "overleaf",
"token_count": 4897
} | 560 |
const SandboxedModule = require('sandboxed-module')
const path = require('path')
const sinon = require('sinon')
const { expect } = require('chai')
const MockResponse = require('../helpers/MockResponse')
const MODULE_PATH = path.join(
__dirname,
'../../../../app/src/Features/PasswordReset/PasswordResetController'
)
describe('PasswordResetController', function () {
beforeEach(function () {
this.email = 'bob@bob.com'
this.user_id = 'mock-user-id'
this.token = 'my security token that was emailed to me'
this.password = 'my new password'
this.req = {
body: {
email: this.email,
passwordResetToken: this.token,
password: this.password,
},
i18n: {
translate() {},
},
session: {},
query: {},
}
this.res = new MockResponse()
this.settings = {}
this.PasswordResetHandler = {
generateAndEmailResetToken: sinon.stub(),
promises: {
setNewUserPassword: sinon
.stub()
.resolves({ found: true, reset: true, userID: this.user_id }),
},
}
this.UserSessionsManager = {
promises: {
revokeAllUserSessions: sinon.stub().resolves(),
},
}
this.UserUpdater = {
promises: {
removeReconfirmFlag: sinon.stub().resolves(),
},
}
this.PasswordResetController = SandboxedModule.require(MODULE_PATH, {
requires: {
'@overleaf/settings': this.settings,
'./PasswordResetHandler': this.PasswordResetHandler,
'../Authentication/AuthenticationController': (this.AuthenticationController = {
getLoggedInUserId: sinon.stub(),
finishLogin: sinon.stub(),
}),
'../User/UserGetter': (this.UserGetter = {
promises: {
getUser: sinon.stub(),
},
}),
'../User/UserSessionsManager': this.UserSessionsManager,
'../User/UserUpdater': this.UserUpdater,
},
})
})
describe('requestReset', function () {
it('should tell the handler to process that email', function (done) {
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
null,
'primary'
)
this.PasswordResetController.requestReset(this.req, this.res)
this.PasswordResetHandler.generateAndEmailResetToken
.calledWith(this.email)
.should.equal(true)
this.res.statusCode.should.equal(200)
done()
})
it('should send a 500 if there is an error', function (done) {
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
new Error('error')
)
this.PasswordResetController.requestReset(this.req, this.res, error => {
expect(error).to.exist
done()
})
})
it("should send a 404 if the email doesn't exist", function (done) {
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
null,
null
)
this.PasswordResetController.requestReset(this.req, this.res)
this.res.statusCode.should.equal(404)
done()
})
it('should send a 404 if the email is registered as a secondard email', function (done) {
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
null,
'secondary'
)
this.PasswordResetController.requestReset(this.req, this.res)
this.res.statusCode.should.equal(404)
done()
})
it('should normalize the email address', function (done) {
this.email = ' UPperCaseEMAILWithSpacesAround@example.Com '
this.req.body.email = this.email
this.PasswordResetHandler.generateAndEmailResetToken.callsArgWith(
1,
null,
'primary'
)
this.PasswordResetController.requestReset(this.req, this.res)
this.PasswordResetHandler.generateAndEmailResetToken
.calledWith(this.email.toLowerCase().trim())
.should.equal(true)
this.res.statusCode.should.equal(200)
done()
})
})
describe('setNewUserPassword', function () {
beforeEach(function () {
this.req.session.resetToken = this.token
})
it('should tell the user handler to reset the password', function (done) {
this.res.sendStatus = code => {
code.should.equal(200)
this.PasswordResetHandler.promises.setNewUserPassword
.calledWith(this.token, this.password)
.should.equal(true)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should preserve spaces in the password', function (done) {
this.password = this.req.body.password = ' oh! clever! spaces around! '
this.res.sendStatus = code => {
code.should.equal(200)
this.PasswordResetHandler.promises.setNewUserPassword.should.have.been.calledWith(
this.token,
this.password
)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should send 404 if the token was not found', function (done) {
this.PasswordResetHandler.promises.setNewUserPassword.resolves({
found: false,
reset: false,
userId: this.user_id,
})
this.res.sendStatus = code => {
code.should.equal(404)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should return 500 if not reset', function (done) {
this.PasswordResetHandler.promises.setNewUserPassword.resolves({
found: true,
reset: false,
userId: this.user_id,
})
this.res.sendStatus = code => {
code.should.equal(500)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should return 400 (Bad Request) if there is no password', function (done) {
this.req.body.password = ''
this.res.sendStatus = code => {
code.should.equal(400)
this.PasswordResetHandler.promises.setNewUserPassword.called.should.equal(
false
)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should return 400 (Bad Request) if there is no passwordResetToken', function (done) {
this.req.body.passwordResetToken = ''
this.res.sendStatus = code => {
code.should.equal(400)
this.PasswordResetHandler.promises.setNewUserPassword.called.should.equal(
false
)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should return 400 (Bad Request) if the password is invalid', function (done) {
this.req.body.password = 'correct horse battery staple'
const err = new Error('bad')
err.name = 'InvalidPasswordError'
this.PasswordResetHandler.promises.setNewUserPassword.rejects(err)
this.res.sendStatus = code => {
code.should.equal(400)
this.PasswordResetHandler.promises.setNewUserPassword.called.should.equal(
true
)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should clear the session.resetToken', function (done) {
this.res.sendStatus = code => {
code.should.equal(200)
this.req.session.should.not.have.property('resetToken')
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should clear sessions', function (done) {
this.res.sendStatus = code => {
this.UserSessionsManager.promises.revokeAllUserSessions.callCount.should.equal(
1
)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should call removeReconfirmFlag', function (done) {
this.res.sendStatus = code => {
this.UserUpdater.promises.removeReconfirmFlag.callCount.should.equal(1)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
describe('catch errors', function () {
it('should return 404 for NotFoundError', function (done) {
const anError = new Error('oops')
anError.name = 'NotFoundError'
this.PasswordResetHandler.promises.setNewUserPassword.rejects(anError)
this.res.sendStatus = code => {
code.should.equal(404)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should return 400 for InvalidPasswordError', function (done) {
const anError = new Error('oops')
anError.name = 'InvalidPasswordError'
this.PasswordResetHandler.promises.setNewUserPassword.rejects(anError)
this.res.sendStatus = code => {
code.should.equal(400)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
it('should return 500 for other errors', function (done) {
const anError = new Error('oops')
this.PasswordResetHandler.promises.setNewUserPassword.rejects(anError)
this.res.sendStatus = code => {
code.should.equal(500)
done()
}
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
})
describe('when doLoginAfterPasswordReset is set', function () {
beforeEach(function () {
this.user = {
_id: this.userId,
email: 'joe@example.com',
}
this.UserGetter.promises.getUser.resolves(this.user)
this.req.session.doLoginAfterPasswordReset = 'true'
})
it('should login user', function (done) {
this.AuthenticationController.finishLogin.callsFake((...args) => {
expect(args[0]).to.equal(this.user)
done()
})
this.PasswordResetController.setNewUserPassword(this.req, this.res)
})
})
})
describe('renderSetPasswordForm', function () {
describe('with token in query-string', function () {
beforeEach(function () {
this.req.query.passwordResetToken = this.token
})
it('should set session.resetToken and redirect', function (done) {
this.req.session.should.not.have.property('resetToken')
this.res.redirect = path => {
path.should.equal('/user/password/set')
this.req.session.resetToken.should.equal(this.token)
done()
}
this.PasswordResetController.renderSetPasswordForm(this.req, this.res)
})
})
describe('with token and email in query-string', function () {
beforeEach(function () {
this.req.query.passwordResetToken = this.token
this.req.query.email = 'foo@bar.com'
})
it('should set session.resetToken and redirect with email', function (done) {
this.req.session.should.not.have.property('resetToken')
this.res.redirect = path => {
path.should.equal('/user/password/set?email=foo%40bar.com')
this.req.session.resetToken.should.equal(this.token)
done()
}
this.PasswordResetController.renderSetPasswordForm(this.req, this.res)
})
})
describe('with token and invalid email in query-string', function () {
beforeEach(function () {
this.req.query.passwordResetToken = this.token
this.req.query.email = 'not-an-email'
})
it('should set session.resetToken and redirect without email', function (done) {
this.req.session.should.not.have.property('resetToken')
this.res.redirect = path => {
path.should.equal('/user/password/set')
this.req.session.resetToken.should.equal(this.token)
done()
}
this.PasswordResetController.renderSetPasswordForm(this.req, this.res)
})
})
describe('with token and non-string email in query-string', function () {
beforeEach(function () {
this.req.query.passwordResetToken = this.token
this.req.query.email = { foo: 'bar' }
})
it('should set session.resetToken and redirect without email', function (done) {
this.req.session.should.not.have.property('resetToken')
this.res.redirect = path => {
path.should.equal('/user/password/set')
this.req.session.resetToken.should.equal(this.token)
done()
}
this.PasswordResetController.renderSetPasswordForm(this.req, this.res)
})
})
describe('without a token in query-string', function () {
describe('with token in session', function () {
beforeEach(function () {
this.req.session.resetToken = this.token
})
it('should render the page, passing the reset token', function (done) {
this.res.render = (templatePath, options) => {
options.passwordResetToken.should.equal(this.req.session.resetToken)
done()
}
this.PasswordResetController.renderSetPasswordForm(this.req, this.res)
})
})
describe('without a token in session', function () {
it('should redirect to the reset request page', function (done) {
this.res.redirect = path => {
path.should.equal('/user/password/reset')
this.req.session.should.not.have.property('resetToken')
done()
}
this.PasswordResetController.renderSetPasswordForm(this.req, this.res)
})
})
})
})
})
| overleaf/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/PasswordReset/PasswordResetControllerTests.js",
"repo_id": "overleaf",
"token_count": 5693
} | 561 |
const { expect } = require('chai')
const SandboxedModule = require('sandboxed-module')
const { ObjectId } = require('mongodb')
const MODULE_PATH = '../../../../app/src/Features/Project/ProjectHelper.js'
describe('ProjectHelper', function () {
beforeEach(function () {
this.project = {
_id: '123213jlkj9kdlsaj',
}
this.user = {
_id: '588f3ddae8ebc1bac07c9fa4',
first_name: 'bjkdsjfk',
features: {},
}
this.adminUser = {
_id: 'admin-user-id',
isAdmin: true,
}
this.Settings = {
allowedImageNames: [
{ imageName: 'texlive-full:2018.1', imageDesc: 'TeX Live 2018' },
{ imageName: 'texlive-full:2019.1', imageDesc: 'TeX Live 2019' },
{
imageName: 'texlive-full:2020.1',
imageDesc: 'TeX Live 2020',
adminOnly: true,
},
],
}
this.ProjectHelper = SandboxedModule.require(MODULE_PATH, {
requires: {
mongodb: { ObjectId },
'@overleaf/settings': this.Settings,
},
})
})
describe('isArchived', function () {
describe('project.archived being an array', function () {
it('returns true if user id is found', function () {
this.project.archived = [
ObjectId('588f3ddae8ebc1bac07c9fa4'),
ObjectId('5c41deb2b4ca500153340809'),
]
expect(
this.ProjectHelper.isArchived(this.project, this.user._id)
).to.equal(true)
})
it('returns false if user id is not found', function () {
this.project.archived = []
expect(
this.ProjectHelper.isArchived(this.project, this.user._id)
).to.equal(false)
})
})
describe('project.archived being a boolean', function () {
it('returns true if archived is true', function () {
this.project.archived = true
expect(
this.ProjectHelper.isArchived(this.project, this.user._id)
).to.equal(true)
})
it('returns false if archived is false', function () {
this.project.archived = false
expect(
this.ProjectHelper.isArchived(this.project, this.user._id)
).to.equal(false)
})
})
describe('project.archived being undefined', function () {
it('returns false if archived is undefined', function () {
this.project.archived = undefined
expect(
this.ProjectHelper.isArchived(this.project, this.user._id)
).to.equal(false)
})
})
})
describe('isTrashed', function () {
it('returns true if user id is found', function () {
this.project.trashed = [
ObjectId('588f3ddae8ebc1bac07c9fa4'),
ObjectId('5c41deb2b4ca500153340809'),
]
expect(
this.ProjectHelper.isTrashed(this.project, this.user._id)
).to.equal(true)
})
it('returns false if user id is not found', function () {
this.project.trashed = []
expect(
this.ProjectHelper.isTrashed(this.project, this.user._id)
).to.equal(false)
})
describe('project.trashed being undefined', function () {
it('returns false if trashed is undefined', function () {
this.project.trashed = undefined
expect(
this.ProjectHelper.isTrashed(this.project, this.user._id)
).to.equal(false)
})
})
})
describe('calculateArchivedArray', function () {
describe('project.archived being an array', function () {
it('returns an array adding the current user id when archiving', function () {
const project = { archived: [] }
const result = this.ProjectHelper.calculateArchivedArray(
project,
ObjectId('5c922599cdb09e014aa7d499'),
'ARCHIVE'
)
expect(result).to.deep.equal([ObjectId('5c922599cdb09e014aa7d499')])
})
it('returns an array without the current user id when unarchiving', function () {
const project = { archived: [ObjectId('5c922599cdb09e014aa7d499')] }
const result = this.ProjectHelper.calculateArchivedArray(
project,
ObjectId('5c922599cdb09e014aa7d499'),
'UNARCHIVE'
)
expect(result).to.deep.equal([])
})
})
describe('project.archived being a boolean and being true', function () {
it('returns an array of all associated user ids when archiving', function () {
const project = {
archived: true,
owner_ref: this.user._id,
collaberator_refs: [
ObjectId('4f2cfb341eb5855a5b000f8b'),
ObjectId('5c45f3bd425ead01488675aa'),
],
readOnly_refs: [ObjectId('5c92243fcdb09e014aa7d487')],
tokenAccessReadAndWrite_refs: [ObjectId('5c922599cdb09e014aa7d499')],
tokenAccessReadOnly_refs: [],
}
const result = this.ProjectHelper.calculateArchivedArray(
project,
this.user._id,
'ARCHIVE'
)
expect(result).to.deep.equal([
this.user._id,
ObjectId('4f2cfb341eb5855a5b000f8b'),
ObjectId('5c45f3bd425ead01488675aa'),
ObjectId('5c92243fcdb09e014aa7d487'),
ObjectId('5c922599cdb09e014aa7d499'),
])
})
it('returns an array of all associated users without the current user id when unarchived', function () {
const project = {
archived: true,
owner_ref: this.user._id,
collaberator_refs: [
ObjectId('4f2cfb341eb5855a5b000f8b'),
ObjectId('5c45f3bd425ead01488675aa'),
ObjectId('5c922599cdb09e014aa7d499'),
],
readOnly_refs: [ObjectId('5c92243fcdb09e014aa7d487')],
tokenAccessReadAndWrite_refs: [ObjectId('5c922599cdb09e014aa7d499')],
tokenAccessReadOnly_refs: [],
}
const result = this.ProjectHelper.calculateArchivedArray(
project,
this.user._id,
'UNARCHIVE'
)
expect(result).to.deep.equal([
ObjectId('4f2cfb341eb5855a5b000f8b'),
ObjectId('5c45f3bd425ead01488675aa'),
ObjectId('5c922599cdb09e014aa7d499'),
ObjectId('5c92243fcdb09e014aa7d487'),
])
})
})
describe('project.archived being a boolean and being false', function () {
it('returns an array adding the current user id when archiving', function () {
const project = { archived: false }
const result = this.ProjectHelper.calculateArchivedArray(
project,
ObjectId('5c922599cdb09e014aa7d499'),
'ARCHIVE'
)
expect(result).to.deep.equal([ObjectId('5c922599cdb09e014aa7d499')])
})
it('returns an empty array when unarchiving', function () {
const project = { archived: false }
const result = this.ProjectHelper.calculateArchivedArray(
project,
ObjectId('5c922599cdb09e014aa7d499'),
'UNARCHIVE'
)
expect(result).to.deep.equal([])
})
})
describe('project.archived not being set', function () {
it('returns an array adding the current user id when archiving', function () {
const project = { archived: undefined }
const result = this.ProjectHelper.calculateArchivedArray(
project,
ObjectId('5c922599cdb09e014aa7d499'),
'ARCHIVE'
)
expect(result).to.deep.equal([ObjectId('5c922599cdb09e014aa7d499')])
})
it('returns an empty array when unarchiving', function () {
const project = { archived: undefined }
const result = this.ProjectHelper.calculateArchivedArray(
project,
ObjectId('5c922599cdb09e014aa7d499'),
'UNARCHIVE'
)
expect(result).to.deep.equal([])
})
})
})
describe('compilerFromV1Engine', function () {
it('returns the correct engine for latex_dvipdf', function () {
expect(this.ProjectHelper.compilerFromV1Engine('latex_dvipdf')).to.equal(
'latex'
)
})
it('returns the correct engine for pdflatex', function () {
expect(this.ProjectHelper.compilerFromV1Engine('pdflatex')).to.equal(
'pdflatex'
)
})
it('returns the correct engine for xelatex', function () {
expect(this.ProjectHelper.compilerFromV1Engine('xelatex')).to.equal(
'xelatex'
)
})
it('returns the correct engine for lualatex', function () {
expect(this.ProjectHelper.compilerFromV1Engine('lualatex')).to.equal(
'lualatex'
)
})
})
describe('getAllowedImagesForUser', function () {
it('filters out admin-only images when the user is anonymous', function () {
const images = this.ProjectHelper.getAllowedImagesForUser(null)
const imageNames = images.map(image => image.imageName)
expect(imageNames).to.deep.equal([
'texlive-full:2018.1',
'texlive-full:2019.1',
])
})
it('filters out admin-only images when the user is not admin', function () {
const images = this.ProjectHelper.getAllowedImagesForUser(this.user)
const imageNames = images.map(image => image.imageName)
expect(imageNames).to.deep.equal([
'texlive-full:2018.1',
'texlive-full:2019.1',
])
})
it('returns all images when the user is admin', function () {
const images = this.ProjectHelper.getAllowedImagesForUser(this.adminUser)
const imageNames = images.map(image => image.imageName)
expect(imageNames).to.deep.equal([
'texlive-full:2018.1',
'texlive-full:2019.1',
'texlive-full:2020.1',
])
})
})
})
| overleaf/web/test/unit/src/Project/ProjectHelperTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Project/ProjectHelperTests.js",
"repo_id": "overleaf",
"token_count": 4341
} | 562 |
/* eslint-disable
node/handle-callback-err,
max-len,
no-return-assign,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const sinon = require('sinon')
const { expect } = require('chai')
const modulePath = require('path').join(
__dirname,
'../../../../app/src/Features/Security/LoginRateLimiter'
)
describe('LoginRateLimiter', function () {
beforeEach(function () {
this.email = 'bob@bob.com'
this.RateLimiter = {
clearRateLimit: sinon.stub(),
addCount: sinon.stub(),
}
return (this.LoginRateLimiter = SandboxedModule.require(modulePath, {
requires: {
'../../infrastructure/RateLimiter': this.RateLimiter,
},
}))
})
describe('processLoginRequest', function () {
beforeEach(function () {
return (this.RateLimiter.addCount = sinon
.stub()
.callsArgWith(1, null, true))
})
it('should call RateLimiter.addCount', function (done) {
return this.LoginRateLimiter.processLoginRequest(
this.email,
(err, allow) => {
this.RateLimiter.addCount.callCount.should.equal(1)
expect(
this.RateLimiter.addCount.lastCall.args[0].endpointName
).to.equal('login')
expect(
this.RateLimiter.addCount.lastCall.args[0].subjectName
).to.equal(this.email)
return done()
}
)
})
describe('when login is allowed', function () {
beforeEach(function () {
return (this.RateLimiter.addCount = sinon
.stub()
.callsArgWith(1, null, true))
})
it('should call pass allow=true', function (done) {
return this.LoginRateLimiter.processLoginRequest(
this.email,
(err, allow) => {
expect(err).to.equal(null)
expect(allow).to.equal(true)
return done()
}
)
})
})
describe('when login is blocked', function () {
beforeEach(function () {
return (this.RateLimiter.addCount = sinon
.stub()
.callsArgWith(1, null, false))
})
it('should call pass allow=false', function (done) {
return this.LoginRateLimiter.processLoginRequest(
this.email,
(err, allow) => {
expect(err).to.equal(null)
expect(allow).to.equal(false)
return done()
}
)
})
})
describe('when addCount produces an error', function () {
beforeEach(function () {
return (this.RateLimiter.addCount = sinon
.stub()
.callsArgWith(1, new Error('woops')))
})
it('should produce an error', function (done) {
return this.LoginRateLimiter.processLoginRequest(
this.email,
(err, allow) => {
expect(err).to.not.equal(null)
expect(err).to.be.instanceof(Error)
return done()
}
)
})
})
})
describe('recordSuccessfulLogin', function () {
beforeEach(function () {
return (this.RateLimiter.clearRateLimit = sinon
.stub()
.callsArgWith(2, null))
})
it('should call clearRateLimit', function (done) {
return this.LoginRateLimiter.recordSuccessfulLogin(this.email, () => {
this.RateLimiter.clearRateLimit.callCount.should.equal(1)
this.RateLimiter.clearRateLimit
.calledWith('login', this.email)
.should.equal(true)
return done()
})
})
})
})
| overleaf/web/test/unit/src/Security/LoginRateLimiterTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Security/LoginRateLimiterTests.js",
"repo_id": "overleaf",
"token_count": 1677
} | 563 |
/* eslint-disable
node/handle-callback-err,
max-len,
no-dupe-keys,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const SandboxedModule = require('sandboxed-module')
const sinon = require('sinon')
const { assert, expect } = require('chai')
const modulePath =
'../../../../app/src/Features/Subscription/SubscriptionGroupHandler'
describe('SubscriptionGroupHandler', function () {
beforeEach(function () {
this.adminUser_id = '12321'
this.newEmail = 'bob@smith.com'
this.user_id = '3121321'
this.email = 'jim@example.com'
this.user = { _id: this.user_id, email: this.newEmail }
this.subscription_id = '31DSd1123D'
this.subscription = {
admin_id: this.adminUser_id,
manager_ids: [this.adminUser_id],
_id: this.subscription_id,
}
this.SubscriptionLocator = {
getUsersSubscription: sinon.stub(),
getSubscriptionByMemberIdAndId: sinon.stub(),
getSubscription: sinon.stub().callsArgWith(1, null, this.subscription),
}
this.UserCreator = {
getUserOrCreateHoldingAccount: sinon
.stub()
.callsArgWith(1, null, this.user),
}
this.SubscriptionUpdater = {
removeUserFromGroup: sinon.stub().callsArgWith(2),
getSubscription: sinon.stub().callsArgWith(2),
}
this.TeamInvitesHandler = { createInvite: sinon.stub().callsArgWith(2) }
this.UserGetter = {
getUser: sinon.stub(),
getUserByAnyEmail: sinon.stub(),
}
this.LimitationsManager = { hasGroupMembersLimitReached: sinon.stub() }
this.OneTimeTokenHandler = {
getValueFromTokenAndExpire: sinon.stub(),
getNewToken: sinon.stub(),
}
this.EmailHandler = { sendEmail: sinon.stub() }
this.Subscription = {
updateOne: sinon.stub().yields(),
updateMany: sinon.stub().yields(),
findOne: sinon.stub().yields(),
}
this.settings = { siteUrl: 'http://www.sharelatex.com' }
this.readStub = sinon.stub()
this.NotificationsBuilder = {
groupPlan: sinon.stub().returns({ read: this.readStub }),
}
this.UserMembershipViewModel = {
build(email) {
return { email }
},
}
return (this.Handler = SandboxedModule.require(modulePath, {
requires: {
'../User/UserCreator': this.UserCreator,
'./SubscriptionUpdater': this.SubscriptionUpdater,
'./SubscriptionLocator': this.SubscriptionLocator,
'../../models/Subscription': {
Subscription: this.Subscription,
},
'../User/UserGetter': this.UserGetter,
'./LimitationsManager': this.LimitationsManager,
'../Security/OneTimeTokenHandler': this.OneTimeTokenHandler,
'../Email/EmailHandler': this.EmailHandler,
'@overleaf/settings': this.settings,
'../Notifications/NotificationsBuilder': this.NotificationsBuilder,
'../UserMembership/UserMembershipViewModel': this
.UserMembershipViewModel,
},
}))
})
describe('removeUserFromGroup', function () {
it('should call the subscription updater to remove the user', function (done) {
return this.Handler.removeUserFromGroup(
this.adminUser_id,
this.user._id,
err => {
this.SubscriptionUpdater.removeUserFromGroup
.calledWith(this.adminUser_id, this.user._id)
.should.equal(true)
return done()
}
)
})
})
describe('replaceUserReferencesInGroups', function () {
beforeEach(function (done) {
this.oldId = 'ba5eba11'
this.newId = '5ca1ab1e'
return this.Handler.replaceUserReferencesInGroups(
this.oldId,
this.newId,
() => done()
)
})
it('replaces the admin_id', function () {
return this.Subscription.updateOne
.calledWith({ admin_id: this.oldId }, { admin_id: this.newId })
.should.equal(true)
})
it('replaces the manager_ids', function () {
this.Subscription.updateMany
.calledWith(
{ manager_ids: 'ba5eba11' },
{ $addToSet: { manager_ids: '5ca1ab1e' } }
)
.should.equal(true)
return this.Subscription.updateMany
.calledWith(
{ manager_ids: 'ba5eba11' },
{ $pull: { manager_ids: 'ba5eba11' } }
)
.should.equal(true)
})
it('replaces the member ids', function () {
this.Subscription.updateMany
.calledWith(
{ member_ids: this.oldId },
{ $addToSet: { member_ids: this.newId } }
)
.should.equal(true)
return this.Subscription.updateMany
.calledWith(
{ member_ids: this.oldId },
{ $pull: { member_ids: this.oldId } }
)
.should.equal(true)
})
})
describe('isUserPartOfGroup', function () {
beforeEach(function () {
return (this.subscription_id = '123ed13123')
})
it('should return true when user is part of subscription', function (done) {
this.SubscriptionLocator.getSubscriptionByMemberIdAndId.callsArgWith(
2,
null,
{ _id: this.subscription_id }
)
return this.Handler.isUserPartOfGroup(
this.user_id,
this.subscription_id,
(err, partOfGroup) => {
partOfGroup.should.equal(true)
return done()
}
)
})
it('should return false when no subscription is found', function (done) {
this.SubscriptionLocator.getSubscriptionByMemberIdAndId.callsArgWith(
2,
null
)
return this.Handler.isUserPartOfGroup(
this.user_id,
this.subscription_id,
(err, partOfGroup) => {
partOfGroup.should.equal(false)
return done()
}
)
})
})
describe('getTotalConfirmedUsersInGroup', function () {
describe('for existing subscriptions', function () {
beforeEach(function () {
return (this.subscription.member_ids = ['12321', '3121321'])
})
it('should call the subscription locator and return 2 users', function (done) {
return this.Handler.getTotalConfirmedUsersInGroup(
this.subscription_id,
(err, count) => {
this.SubscriptionLocator.getSubscription
.calledWith(this.subscription_id)
.should.equal(true)
count.should.equal(2)
return done()
}
)
})
})
describe('for nonexistent subscriptions', function () {
it('should return undefined', function (done) {
return this.Handler.getTotalConfirmedUsersInGroup(
'fake-id',
(err, count) => {
expect(count).not.to.exist
return done()
}
)
})
})
})
})
| overleaf/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/Subscription/SubscriptionGroupHandlerTests.js",
"repo_id": "overleaf",
"token_count": 3072
} | 564 |
const { ObjectId } = require('mongodb')
const SandboxedModule = require('sandboxed-module')
const path = require('path')
const sinon = require('sinon')
const modulePath = path.join(
__dirname,
'../../../../app/src/Features/ThirdPartyDataStore/TpdsUpdateSender.js'
)
const projectId = 'project_id_here'
const userId = ObjectId()
const readOnlyRef = ObjectId()
const collaberatorRef = ObjectId()
const projectName = 'project_name_here'
const thirdPartyDataStoreApiUrl = 'http://third-party-json-store.herokuapp.com'
const siteUrl = 'http://www.localhost:3000'
const filestoreUrl = 'filestore.sharelatex.com'
const projectArchiverUrl = 'project-archiver.overleaf.com'
describe('TpdsUpdateSender', function () {
beforeEach(function () {
this.fakeUser = {
_id: '12390i',
}
this.requestQueuer = function (queue, meth, opts, callback) {}
const memberIds = [userId, collaberatorRef, readOnlyRef]
this.CollaboratorsGetter = {
promises: {
getInvitedMemberIds: sinon.stub().resolves(memberIds),
},
}
this.docstoreUrl = 'docstore.sharelatex.env'
this.request = sinon.stub().resolves()
this.settings = {
siteUrl,
apis: {
thirdPartyDataStore: { url: thirdPartyDataStoreApiUrl },
filestore: {
url: filestoreUrl,
},
docstore: {
pubUrl: this.docstoreUrl,
},
},
}
const getUsers = sinon.stub().resolves(
memberIds.slice(1).map(userId => {
return { _id: userId }
})
)
this.UserGetter = {
promises: { getUsers },
}
this.updateSender = SandboxedModule.require(modulePath, {
requires: {
mongodb: { ObjectId },
'@overleaf/settings': this.settings,
'request-promise-native': this.request,
'../Collaborators/CollaboratorsGetter': this.CollaboratorsGetter,
'../User/UserGetter.js': this.UserGetter,
'@overleaf/metrics': {
inc() {},
},
},
})
})
describe('enqueue', function () {
it('should not call request if there is no tpdsworker url', async function () {
await this.updateSender.promises.enqueue(null, null, null)
this.request.should.not.have.been.called
})
it('should post the message to the tpdsworker', async function () {
this.settings.apis.tpdsworker = { url: 'www.tpdsworker.env' }
const group0 = 'myproject'
const method0 = 'somemethod0'
const job0 = 'do something'
await this.updateSender.promises.enqueue(group0, method0, job0)
const args = this.request.firstCall.args[0]
args.json.group.should.equal(group0)
args.json.job.should.equal(job0)
args.json.method.should.equal(method0)
args.uri.should.equal(
'www.tpdsworker.env/enqueue/web_to_tpds_http_requests'
)
})
})
describe('sending updates', function () {
beforeEach(function () {
this.settings.apis.tpdsworker = { url: 'www.tpdsworker.env' }
})
it('queues a post the file with user and file id', async function () {
const fileId = '4545345'
const path = '/some/path/here.jpg'
await this.updateSender.promises.addFile({
project_id: projectId,
file_id: fileId,
path,
project_name: projectName,
})
const {
group: group0,
job: job0,
method: method0,
} = this.request.firstCall.args[0].json
group0.should.equal(userId)
method0.should.equal('pipeStreamFrom')
job0.method.should.equal('post')
job0.streamOrigin.should.equal(
`${filestoreUrl}/project/${projectId}/file/${fileId}`
)
const expectedUrl = `${thirdPartyDataStoreApiUrl}/user/${userId}/entity/${encodeURIComponent(
projectName
)}${encodeURIComponent(path)}`
job0.uri.should.equal(expectedUrl)
job0.headers.sl_all_user_ids.should.equal(JSON.stringify([userId]))
job0.headers.sl_project_owner_user_id.should.equal(userId)
const { group: group1, job: job1 } = this.request.secondCall.args[0].json
group1.should.equal(collaberatorRef)
job1.headers.sl_all_user_ids.should.equal(
JSON.stringify([collaberatorRef])
)
job1.headers.sl_project_owner_user_id.should.equal(userId)
const { group: group2, job: job2 } = this.request.thirdCall.args[0].json
group2.should.equal(readOnlyRef)
job2.headers.sl_all_user_ids.should.equal(JSON.stringify([readOnlyRef]))
job2.headers.sl_project_owner_user_id.should.equal(userId)
this.UserGetter.promises.getUsers.should.have.been.calledOnce.and.calledWith(
{
_id: {
$in: [collaberatorRef, readOnlyRef],
},
'dropbox.access_token.uid': { $ne: null },
},
{ _id: 1 }
)
})
it('post doc with stream origin of docstore', async function () {
const docId = '4545345'
const path = '/some/path/here.tex'
const lines = ['line1', 'line2', 'line3']
await this.updateSender.promises.addDoc({
project_id: projectId,
doc_id: docId,
path,
docLines: lines,
project_name: projectName,
})
const {
group: group0,
job: job0,
method: method0,
} = this.request.firstCall.args[0].json
group0.should.equal(userId)
method0.should.equal('pipeStreamFrom')
job0.method.should.equal('post')
const expectedUrl = `${thirdPartyDataStoreApiUrl}/user/${userId}/entity/${encodeURIComponent(
projectName
)}${encodeURIComponent(path)}`
job0.uri.should.equal(expectedUrl)
job0.streamOrigin.should.equal(
`${this.docstoreUrl}/project/${projectId}/doc/${docId}/raw`
)
job0.headers.sl_all_user_ids.should.eql(JSON.stringify([userId]))
const { group: group1, job: job1 } = this.request.secondCall.args[0].json
group1.should.equal(collaberatorRef)
job1.headers.sl_all_user_ids.should.equal(
JSON.stringify([collaberatorRef])
)
const { group: group2, job: job2 } = this.request.thirdCall.args[0].json
group2.should.equal(readOnlyRef)
job2.headers.sl_all_user_ids.should.equal(JSON.stringify([readOnlyRef]))
this.UserGetter.promises.getUsers.should.have.been.calledOnce.and.calledWith(
{
_id: {
$in: [collaberatorRef, readOnlyRef],
},
'dropbox.access_token.uid': { $ne: null },
},
{ _id: 1 }
)
})
it('deleting entity', async function () {
const path = '/path/here/t.tex'
await this.updateSender.promises.deleteEntity({
project_id: projectId,
path,
project_name: projectName,
})
const {
group: group0,
job: job0,
method: method0,
} = this.request.firstCall.args[0].json
group0.should.equal(userId)
method0.should.equal('standardHttpRequest')
job0.method.should.equal('delete')
const expectedUrl = `${thirdPartyDataStoreApiUrl}/user/${userId}/entity/${encodeURIComponent(
projectName
)}${encodeURIComponent(path)}`
job0.headers.sl_all_user_ids.should.eql(JSON.stringify([userId]))
job0.uri.should.equal(expectedUrl)
const { group: group1, job: job1 } = this.request.secondCall.args[0].json
group1.should.equal(collaberatorRef)
job1.headers.sl_all_user_ids.should.equal(
JSON.stringify([collaberatorRef])
)
const { group: group2, job: job2 } = this.request.thirdCall.args[0].json
group2.should.equal(readOnlyRef)
job2.headers.sl_all_user_ids.should.equal(JSON.stringify([readOnlyRef]))
this.UserGetter.promises.getUsers.should.have.been.calledOnce.and.calledWith(
{
_id: {
$in: [collaberatorRef, readOnlyRef],
},
'dropbox.access_token.uid': { $ne: null },
},
{ _id: 1 }
)
})
it('moving entity', async function () {
const startPath = 'staring/here/file.tex'
const endPath = 'ending/here/file.tex'
await this.updateSender.promises.moveEntity({
project_id: projectId,
startPath,
endPath,
project_name: projectName,
})
const {
group: group0,
job: job0,
method: method0,
} = this.request.firstCall.args[0].json
group0.should.equal(userId)
method0.should.equal('standardHttpRequest')
job0.method.should.equal('put')
job0.uri.should.equal(
`${thirdPartyDataStoreApiUrl}/user/${userId}/entity`
)
job0.json.startPath.should.equal(`/${projectName}/${startPath}`)
job0.json.endPath.should.equal(`/${projectName}/${endPath}`)
job0.headers.sl_all_user_ids.should.eql(JSON.stringify([userId]))
const { group: group1, job: job1 } = this.request.secondCall.args[0].json
group1.should.equal(collaberatorRef)
job1.headers.sl_all_user_ids.should.equal(
JSON.stringify([collaberatorRef])
)
const { group: group2, job: job2 } = this.request.thirdCall.args[0].json
group2.should.equal(readOnlyRef)
job2.headers.sl_all_user_ids.should.equal(JSON.stringify([readOnlyRef]))
this.UserGetter.promises.getUsers.should.have.been.calledOnce.and.calledWith(
{
_id: {
$in: [collaberatorRef, readOnlyRef],
},
'dropbox.access_token.uid': { $ne: null },
},
{ _id: 1 }
)
})
it('should be able to rename a project using the move entity func', async function () {
const oldProjectName = '/oldProjectName/'
const newProjectName = '/newProjectName/'
await this.updateSender.promises.moveEntity({
project_id: projectId,
project_name: oldProjectName,
newProjectName,
})
const {
group: group0,
job: job0,
method: method0,
} = this.request.firstCall.args[0].json
group0.should.equal(userId)
method0.should.equal('standardHttpRequest')
job0.method.should.equal('put')
job0.uri.should.equal(
`${thirdPartyDataStoreApiUrl}/user/${userId}/entity`
)
job0.json.startPath.should.equal(oldProjectName)
job0.json.endPath.should.equal(newProjectName)
job0.headers.sl_all_user_ids.should.eql(JSON.stringify([userId]))
const { group: group1, job: job1 } = this.request.secondCall.args[0].json
group1.should.equal(collaberatorRef)
job1.headers.sl_all_user_ids.should.equal(
JSON.stringify([collaberatorRef])
)
const { group: group2, job: job2 } = this.request.thirdCall.args[0].json
group2.should.equal(readOnlyRef)
job2.headers.sl_all_user_ids.should.equal(JSON.stringify([readOnlyRef]))
this.UserGetter.promises.getUsers.should.have.been.calledOnce.and.calledWith(
{
_id: {
$in: [collaberatorRef, readOnlyRef],
},
'dropbox.access_token.uid': { $ne: null },
},
{ _id: 1 }
)
})
it('pollDropboxForUser', async function () {
await this.updateSender.promises.pollDropboxForUser(userId)
const {
group: group0,
job: job0,
method: method0,
} = this.request.firstCall.args[0].json
group0.should.equal(`poll-dropbox:${userId}`)
method0.should.equal('standardHttpRequest')
job0.method.should.equal('post')
job0.uri.should.equal(`${thirdPartyDataStoreApiUrl}/user/poll`)
job0.json.user_ids[0].should.equal(userId)
})
})
describe('deleteProject', function () {
it('should not call request if there is no project archiver url', async function () {
await this.updateSender.promises.deleteProject({ project_id: projectId })
this.request.should.not.have.been.called
})
it('should make a delete request to project archiver', async function () {
this.settings.apis.project_archiver = { url: projectArchiverUrl }
await this.updateSender.promises.deleteProject({ project_id: projectId })
const { uri, method } = this.request.firstCall.args[0]
method.should.equal('delete')
uri.should.equal(`${projectArchiverUrl}/project/${projectId}`)
})
})
})
| overleaf/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateSenderTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/ThirdPartyDataStore/TpdsUpdateSenderTests.js",
"repo_id": "overleaf",
"token_count": 5421
} | 565 |
const { ObjectId } = require('mongodb')
const SandboxedModule = require('sandboxed-module')
const assert = require('assert')
const moment = require('moment')
const path = require('path')
const sinon = require('sinon')
const modulePath = path.join(
__dirname,
'../../../../app/src/Features/User/UserGetter'
)
const { expect } = require('chai')
const Errors = require('../../../../app/src/Features/Errors/Errors')
const {
normalizeQuery,
normalizeMultiQuery,
} = require('../../../../app/src/Features/Helpers/Mongo')
describe('UserGetter', function () {
beforeEach(function () {
this.fakeUser = {
_id: '12390i',
email: 'email2@foo.bar',
emails: [
{
email: 'email1@foo.bar',
reversedHostname: 'rab.oof',
confirmedAt: new Date(),
},
{ email: 'email2@foo.bar', reversedHostname: 'rab.oof' },
],
}
this.findOne = sinon.stub().callsArgWith(2, null, this.fakeUser)
this.findToArrayStub = sinon.stub().yields(null, [this.fakeUser])
this.find = sinon.stub().returns({ toArray: this.findToArrayStub })
this.Mongo = {
db: {
users: {
findOne: this.findOne,
find: this.find,
},
},
ObjectId,
}
this.getUserAffiliations = sinon.stub().resolves([])
this.UserGetter = SandboxedModule.require(modulePath, {
requires: {
'../Helpers/Mongo': { normalizeQuery, normalizeMultiQuery },
'../../infrastructure/mongodb': this.Mongo,
'@overleaf/metrics': {
timeAsyncMethod: sinon.stub(),
},
'@overleaf/settings': (this.settings = {
reconfirmNotificationDays: 14,
}),
'../Institutions/InstitutionsAPI': {
promises: {
getUserAffiliations: this.getUserAffiliations,
},
},
'../../infrastructure/Features': {
hasFeature: sinon.stub().returns(true),
},
'../../models/User': {
User: (this.User = {}),
},
},
})
})
describe('getSsoUsersAtInstitution', function () {
it('should throw an error when no projection is passed', function (done) {
this.UserGetter.getSsoUsersAtInstitution(1, undefined, error => {
expect(error).to.exist
expect(error.message).to.equal('missing projection')
done()
})
})
})
describe('getUser', function () {
it('should get user', function (done) {
const query = { _id: '000000000000000000000000' }
const projection = { email: 1 }
this.UserGetter.getUser(query, projection, (error, user) => {
expect(error).to.not.exist
this.findOne.called.should.equal(true)
this.findOne.calledWith(query, { projection }).should.equal(true)
user.should.deep.equal(this.fakeUser)
done()
})
})
it('should not allow null query', function (done) {
this.UserGetter.getUser(null, {}, error => {
error.should.exist
error.message.should.equal('no query provided')
done()
})
})
})
describe('getUsers', function () {
it('should get users with array of userIds', function (done) {
const query = [new ObjectId()]
const projection = { email: 1 }
this.UserGetter.getUsers(query, projection, (error, users) => {
expect(error).to.not.exist
this.find.should.have.been.calledWithMatch(
{ _id: { $in: query } },
{ projection }
)
users.should.deep.equal([this.fakeUser])
done()
})
})
it('should not allow null query', function (done) {
this.UserGetter.getUser(null, {}, error => {
error.should.exist
error.message.should.equal('no query provided')
done()
})
})
})
describe('getUserFullEmails', function () {
it('should get user', function (done) {
this.UserGetter.promises.getUser = sinon.stub().resolves(this.fakeUser)
const projection = { email: 1, emails: 1, samlIdentifiers: 1 }
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
this.UserGetter.promises.getUser.called.should.equal(true)
this.UserGetter.promises.getUser
.calledWith(this.fakeUser._id, projection)
.should.equal(true)
done()
}
)
})
it('should fetch emails data', function (done) {
this.UserGetter.promises.getUser = sinon.stub().resolves(this.fakeUser)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
assert.deepEqual(fullEmails, [
{
email: 'email1@foo.bar',
reversedHostname: 'rab.oof',
confirmedAt: this.fakeUser.emails[0].confirmedAt,
emailHasInstitutionLicence: false,
default: false,
},
{
email: 'email2@foo.bar',
reversedHostname: 'rab.oof',
emailHasInstitutionLicence: false,
default: true,
},
])
done()
}
)
})
it('should merge affiliation data', function (done) {
this.UserGetter.promises.getUser = sinon.stub().resolves(this.fakeUser)
const affiliationsData = [
{
email: 'email1@foo.bar',
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: {
name: 'University Name',
isUniversity: true,
confirmed: true,
},
portal: undefined,
},
]
this.getUserAffiliations.resolves(affiliationsData)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
assert.deepEqual(fullEmails, [
{
email: 'email1@foo.bar',
reversedHostname: 'rab.oof',
confirmedAt: this.fakeUser.emails[0].confirmedAt,
default: false,
emailHasInstitutionLicence: true,
affiliation: {
institution: affiliationsData[0].institution,
inferred: affiliationsData[0].inferred,
department: affiliationsData[0].department,
role: affiliationsData[0].role,
lastDayToReconfirm: undefined,
licence: affiliationsData[0].licence,
inReconfirmNotificationPeriod: false,
pastReconfirmDate: false,
portal: undefined,
},
},
{
email: 'email2@foo.bar',
reversedHostname: 'rab.oof',
emailHasInstitutionLicence: false,
default: true,
},
])
done()
}
)
})
it('should merge SAML identifier', function (done) {
const fakeSamlIdentifiers = [
{ providerId: 'saml_id', exteranlUserId: 'whatever' },
]
const fakeUserWithSaml = this.fakeUser
fakeUserWithSaml.emails[0].samlProviderId = 'saml_id'
fakeUserWithSaml.samlIdentifiers = fakeSamlIdentifiers
this.UserGetter.promises.getUser = sinon.stub().resolves(this.fakeUser)
this.getUserAffiliations.resolves([])
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
assert.deepEqual(fullEmails, [
{
email: 'email1@foo.bar',
reversedHostname: 'rab.oof',
confirmedAt: this.fakeUser.emails[0].confirmedAt,
default: false,
emailHasInstitutionLicence: false,
samlProviderId: 'saml_id',
samlIdentifier: fakeSamlIdentifiers[0],
},
{
email: 'email2@foo.bar',
reversedHostname: 'rab.oof',
emailHasInstitutionLicence: false,
default: true,
},
])
done()
}
)
})
it('should get user when it has no emails field', function (done) {
this.fakeUser = {
_id: '12390i',
email: 'email2@foo.bar',
}
this.UserGetter.promises.getUser = sinon.stub().resolves(this.fakeUser)
const projection = { email: 1, emails: 1, samlIdentifiers: 1 }
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
this.UserGetter.promises.getUser.called.should.equal(true)
this.UserGetter.promises.getUser
.calledWith(this.fakeUser._id, projection)
.should.equal(true)
assert.deepEqual(fullEmails, [])
done()
}
)
})
describe('affiliation reconfirmation', function () {
const institutionNonSSO = {
id: 1,
name: 'University Name',
commonsAccount: true,
isUniversity: true,
confirmed: true,
ssoBeta: false,
ssoEnabled: false,
maxConfirmationMonths: 12,
}
const institutionSSO = {
id: 2,
name: 'SSO University Name',
isUniversity: true,
confirmed: true,
ssoBeta: false,
ssoEnabled: true,
maxConfirmationMonths: 12,
}
describe('non-SSO institutions', function () {
const email1 = 'leonard@example-affiliation.com'
const email2 = 'mccoy@example-affiliation.com'
const affiliationsData = [
{
email: email1,
role: 'Prof',
department: 'Medicine',
inferred: false,
licence: 'pro_plus',
institution: institutionNonSSO,
},
{
email: email2,
role: 'Prof',
department: 'Medicine',
inferred: false,
licence: 'pro_plus',
institution: institutionNonSSO,
},
]
it('should flag inReconfirmNotificationPeriod for all affiliations in period', function (done) {
const user = {
_id: '12390i',
email: email1,
emails: [
{
email: email1,
reversedHostname: 'moc.noitailiffa-elpmaxe',
confirmedAt: moment()
.subtract(
institutionNonSSO.maxConfirmationMonths + 2,
'months'
)
.toDate(),
default: true,
},
{
email: email2,
reversedHostname: 'moc.noitailiffa-elpmaxe',
confirmedAt: moment()
.subtract(
institutionNonSSO.maxConfirmationMonths + 1,
'months'
)
.toDate(),
},
],
}
this.getUserAffiliations.resolves(affiliationsData)
this.UserGetter.promises.getUser = sinon.stub().resolves(user)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
expect(
fullEmails[0].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
expect(
fullEmails[1].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
done()
}
)
})
it('should not flag affiliations outside of notification period', function (done) {
const aboutToBeWithinPeriod = moment()
.subtract(institutionNonSSO.maxConfirmationMonths, 'months')
.add(15, 'days')
.toDate() // expires in 15 days
const user = {
_id: '12390i',
email: email1,
emails: [
{
email: email1,
reversedHostname: 'moc.noitailiffa-elpmaxe',
confirmedAt: new Date(),
default: true,
},
{
email: email2,
reversedHostname: 'moc.noitailiffa-elpmaxe',
confirmedAt: aboutToBeWithinPeriod,
},
],
}
this.getUserAffiliations.resolves(affiliationsData)
this.UserGetter.promises.getUser = sinon.stub().resolves(user)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
expect(
fullEmails[0].affiliation.inReconfirmNotificationPeriod
).to.equal(false)
expect(
fullEmails[1].affiliation.inReconfirmNotificationPeriod
).to.equal(false)
done()
}
)
})
})
describe('SSO institutions', function () {
it('should flag only linked email, if in notification period', function (done) {
const email1 = 'email1@sso.bar'
const email2 = 'email2@sso.bar'
const email3 = 'email3@sso.bar'
const affiliationsData = [
{
email: email1,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionSSO,
},
{
email: email2,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionSSO,
},
{
email: email3,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionSSO,
},
]
const user = {
_id: '12390i',
email: email1,
emails: [
{
email: email1,
reversedHostname: 'rab.oss',
confirmedAt: new Date('2019-09-24'),
reconfirmedAt: new Date('2019-09-24'),
default: true,
},
{
email: email2,
reversedHostname: 'rab.oss',
confirmedAt: new Date('2019-09-24'),
reconfirmedAt: new Date('2019-09-24'),
samlProviderId: institutionSSO.id,
},
{
email: email3,
reversedHostname: 'rab.oss',
confirmedAt: new Date('2019-09-24'),
reconfirmedAt: new Date('2019-09-24'),
},
],
samlIdentifiers: [
{
providerId: institutionSSO.id,
externalUserId: 'abc123',
},
],
}
this.getUserAffiliations.resolves(affiliationsData)
this.UserGetter.promises.getUser = sinon.stub().resolves(user)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
expect(
fullEmails[0].affiliation.inReconfirmNotificationPeriod
).to.equal(false)
expect(
fullEmails[1].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
expect(
fullEmails[2].affiliation.inReconfirmNotificationPeriod
).to.equal(false)
done()
}
)
})
})
describe('multiple institution affiliations', function () {
it('should flag each institution', function (done) {
const email1 = 'email1@sso.bar'
const email2 = 'email2@sso.bar'
const email3 = 'email3@foo.bar'
const email4 = 'email4@foo.bar'
const affiliationsData = [
{
email: email1,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionSSO,
},
{
email: email2,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionSSO,
},
{
email: email3,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionNonSSO,
},
{
email: email4,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionNonSSO,
},
]
const user = {
_id: '12390i',
email: email1,
emails: [
{
email: email1,
reversedHostname: 'rab.oss',
confirmedAt: '2019-09-24T20:25:08.503Z',
default: true,
},
{
email: email2,
reversedHostname: 'rab.oss',
confirmedAt: new Date('2019-09-24T20:25:08.503Z'),
samlProviderId: institutionSSO.id,
},
{
email: email3,
reversedHostname: 'rab.oof',
confirmedAt: new Date('2019-10-24T20:25:08.503Z'),
},
{
email: email4,
reversedHostname: 'rab.oof',
confirmedAt: new Date('2019-09-24T20:25:08.503Z'),
},
],
samlIdentifiers: [
{
providerId: institutionSSO.id,
externalUserId: 'abc123',
},
],
}
this.getUserAffiliations.resolves(affiliationsData)
this.UserGetter.promises.getUser = sinon.stub().resolves(user)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
expect(
fullEmails[0].affiliation.inReconfirmNotificationPeriod
).to.to.equal(false)
expect(
fullEmails[1].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
expect(
fullEmails[2].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
expect(
fullEmails[3].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
done()
}
)
})
})
describe('reconfirmedAt', function () {
it('only use confirmedAt when no reconfirmedAt', function (done) {
const email1 = 'email1@foo.bar'
const email2 = 'email2@foo.bar'
const email3 = 'email3@foo.bar'
const affiliationsData = [
{
email: email1,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionNonSSO,
},
{
email: email2,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionNonSSO,
},
{
email: email3,
role: 'Prof',
department: 'Maths',
inferred: false,
licence: 'pro_plus',
institution: institutionNonSSO,
},
]
const user = {
_id: '12390i',
email: email1,
emails: [
{
email: email1,
reversedHostname: 'rab.oof',
confirmedAt: moment().subtract(
institutionSSO.maxConfirmationMonths * 2,
'months'
),
reconfirmedAt: moment().subtract(
institutionSSO.maxConfirmationMonths * 3,
'months'
),
default: true,
},
{
email: email2,
reversedHostname: 'rab.oof',
confirmedAt: moment().subtract(
institutionSSO.maxConfirmationMonths * 3,
'months'
),
reconfirmedAt: moment().subtract(
institutionSSO.maxConfirmationMonths * 2,
'months'
),
},
{
email: email3,
reversedHostname: 'rab.oof',
confirmedAt: moment().subtract(
institutionSSO.maxConfirmationMonths * 4,
'months'
),
reconfirmedAt: moment().subtract(
institutionSSO.maxConfirmationMonths * 4,
'months'
),
},
],
}
this.getUserAffiliations.resolves(affiliationsData)
this.UserGetter.promises.getUser = sinon.stub().resolves(user)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
expect(
fullEmails[0].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
expect(
fullEmails[1].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
expect(
fullEmails[2].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
done()
}
)
})
})
describe('before reconfirmation period expires and within reconfirmation notification period', function () {
const email = 'leonard@example-affiliation.com'
it('should flag the email', function (done) {
const confirmedAt = moment()
.subtract(institutionNonSSO.maxConfirmationMonths, 'months')
.subtract(14, 'days')
.toDate() // expires in 14 days
const affiliationsData = [
{
email,
role: 'Prof',
department: 'Medicine',
inferred: false,
licence: 'pro_plus',
institution: institutionNonSSO,
},
]
const user = {
_id: '12390i',
email,
emails: [
{
email,
confirmedAt,
default: true,
},
],
}
this.getUserAffiliations.resolves(affiliationsData)
this.UserGetter.promises.getUser = sinon.stub().resolves(user)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
expect(
fullEmails[0].affiliation.inReconfirmNotificationPeriod
).to.equal(true)
done()
}
)
})
})
describe('when no Settings.reconfirmNotificationDays', function () {
it('should always return inReconfirmNotificationPeriod:false', function (done) {
const email1 = 'email1@sso.bar'
const email2 = 'email2@foo.bar'
const email3 = 'email3@foo.bar'
const confirmedAtAboutToExpire = moment()
.subtract(institutionNonSSO.maxConfirmationMonths, 'months')
.subtract(14, 'days')
.toDate() // expires in 14 days
const affiliationsData = [
{
email: email1,
institution: institutionSSO,
},
{
email: email2,
institution: institutionNonSSO,
},
{
email: email3,
institution: institutionNonSSO,
},
]
const user = {
_id: '12390i',
email: email1,
emails: [
{
email: email1,
confirmedAt: confirmedAtAboutToExpire,
default: true,
samlProviderId: institutionSSO.id,
},
{
email: email2,
confirmedAt: new Date('2019-09-24T20:25:08.503Z'),
},
{
email: email3,
confirmedAt: new Date('2019-10-24T20:25:08.503Z'),
},
],
samlIdentifiers: [
{
providerId: institutionSSO.id,
externalUserId: 'abc123',
},
],
}
this.settings.reconfirmNotificationDays = undefined
this.getUserAffiliations.resolves(affiliationsData)
this.UserGetter.promises.getUser = sinon.stub().resolves(user)
this.UserGetter.getUserFullEmails(
this.fakeUser._id,
(error, fullEmails) => {
expect(error).to.not.exist
expect(
fullEmails[0].affiliation.inReconfirmNotificationPeriod
).to.to.equal(false)
expect(
fullEmails[1].affiliation.inReconfirmNotificationPeriod
).to.equal(false)
expect(
fullEmails[2].affiliation.inReconfirmNotificationPeriod
).to.equal(false)
done()
}
)
})
})
})
})
describe('getUserbyMainEmail', function () {
it('query user by main email', function (done) {
const email = 'hello@world.com'
const projection = { emails: 1 }
this.UserGetter.getUserByMainEmail(email, projection, (error, user) => {
expect(error).to.not.exist
this.findOne.called.should.equal(true)
this.findOne.calledWith({ email }, { projection }).should.equal(true)
done()
})
})
it('return user if found', function (done) {
const email = 'hello@world.com'
this.UserGetter.getUserByMainEmail(email, (error, user) => {
expect(error).to.not.exist
user.should.deep.equal(this.fakeUser)
done()
})
})
it('trim email', function (done) {
const email = 'hello@world.com'
this.UserGetter.getUserByMainEmail(` ${email} `, (error, user) => {
expect(error).to.not.exist
this.findOne.called.should.equal(true)
this.findOne.calledWith({ email }).should.equal(true)
done()
})
})
})
describe('getUserByAnyEmail', function () {
it('query user for any email', function (done) {
const email = 'hello@world.com'
const expectedQuery = {
emails: { $exists: true },
'emails.email': email,
}
const projection = { emails: 1 }
this.UserGetter.getUserByAnyEmail(
` ${email} `,
projection,
(error, user) => {
expect(error).to.not.exist
this.findOne
.calledWith(expectedQuery, { projection })
.should.equal(true)
user.should.deep.equal(this.fakeUser)
done()
}
)
})
it('query contains $exists:true so partial index is used', function (done) {
const expectedQuery = {
emails: { $exists: true },
'emails.email': '',
}
this.UserGetter.getUserByAnyEmail('', {}, (error, user) => {
expect(error).to.not.exist
this.findOne
.calledWith(expectedQuery, { projection: {} })
.should.equal(true)
done()
})
})
it('checks main email as well', function (done) {
this.findOne.callsArgWith(2, null, null)
const email = 'hello@world.com'
const projection = { emails: 1 }
this.UserGetter.getUserByAnyEmail(
` ${email} `,
projection,
(error, user) => {
expect(error).to.not.exist
this.findOne.calledTwice.should.equal(true)
this.findOne.calledWith({ email }, { projection }).should.equal(true)
done()
}
)
})
})
describe('getUsersByHostname', function () {
it('should find user by hostname', function (done) {
const hostname = 'bar.foo'
const expectedQuery = {
emails: { $exists: true },
'emails.reversedHostname': hostname.split('').reverse().join(''),
}
const projection = { emails: 1 }
this.UserGetter.getUsersByHostname(
hostname,
projection,
(error, users) => {
expect(error).to.not.exist
this.find.calledOnce.should.equal(true)
this.find.calledWith(expectedQuery, { projection }).should.equal(true)
done()
}
)
})
})
describe('getUsersByAnyConfirmedEmail', function () {
it('should find users by confirmed email', function (done) {
const emails = ['confirmed@example.com']
this.UserGetter.getUsersByAnyConfirmedEmail(emails, (error, users) => {
expect(error).to.not.exist
expect(this.find).to.be.calledOnceWith(
{
'emails.email': { $in: emails }, // use the index on emails.email
emails: {
$exists: true,
$elemMatch: {
email: { $in: emails },
confirmedAt: { $exists: true },
},
},
},
{ projection: {} }
)
done()
})
})
})
describe('getUsersByV1Id', function () {
it('should find users by list of v1 ids', function (done) {
const v1Ids = [501]
const expectedQuery = {
'overleaf.id': { $in: v1Ids },
}
const projection = { emails: 1 }
this.UserGetter.getUsersByV1Ids(v1Ids, projection, (error, users) => {
expect(error).to.not.exist
this.find.calledOnce.should.equal(true)
this.find.calledWith(expectedQuery, { projection }).should.equal(true)
done()
})
})
})
describe('ensureUniqueEmailAddress', function () {
beforeEach(function () {
this.UserGetter.getUserByAnyEmail = sinon.stub()
})
it('should return error if existing user is found', function (done) {
this.UserGetter.getUserByAnyEmail.callsArgWith(1, null, this.fakeUser)
this.UserGetter.ensureUniqueEmailAddress(this.newEmail, err => {
expect(err).to.exist
expect(err).to.be.an.instanceof(Errors.EmailExistsError)
done()
})
})
it('should return null if no user is found', function (done) {
this.UserGetter.getUserByAnyEmail.callsArgWith(1)
this.UserGetter.ensureUniqueEmailAddress(this.newEmail, err => {
expect(err).not.to.exist
done()
})
})
})
})
| overleaf/web/test/unit/src/User/UserGetterTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/User/UserGetterTests.js",
"repo_id": "overleaf",
"token_count": 16524
} | 566 |
/* eslint-disable
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* DS206: Consider reworking classes to avoid initClass
* DS207: Consider shorter variations of null checks
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sinon = require('sinon')
class MockResponse {
static initClass() {
this.prototype.setContentDisposition = sinon.stub()
this.prototype.header = sinon.stub()
this.prototype.contentType = sinon.stub()
}
constructor() {
this.rendered = false
this.redirected = false
this.returned = false
this.headers = {}
}
render(template, variables) {
this.success = true
this.rendered = true
this.returned = true
this.renderedTemplate = template
this.renderedVariables = variables
if (this.callback != null) {
return this.callback()
}
}
redirect(url) {
this.success = true
this.redirected = true
this.returned = true
this.redirectedTo = url
if (this.callback != null) {
return this.callback()
}
}
sendStatus(status) {
if (arguments.length < 2) {
if (typeof status !== 'number') {
status = 200
}
}
this.statusCode = status
this.returned = true
if (status >= 200 && status < 300) {
this.success = true
} else {
this.success = false
}
if (this.callback != null) {
return this.callback()
}
}
send(status, body) {
if (arguments.length < 2) {
if (typeof status !== 'number') {
body = status
status = this.statusCode || 200
}
}
this.statusCode = status
this.returned = true
if (status >= 200 && status < 300) {
this.success = true
} else {
this.success = false
}
if (body) {
this.body = body
}
if (this.callback != null) {
return this.callback()
}
}
json(status, body) {
if (arguments.length < 2) {
if (typeof status !== 'number') {
body = status
status = this.statusCode || 200
}
}
this.statusCode = status
this.returned = true
this.type = 'application/json'
if (status >= 200 && status < 300) {
this.success = true
} else {
this.success = false
}
if (body) {
this.body = JSON.stringify(body)
}
if (this.callback != null) {
return this.callback()
}
}
status(status) {
this.statusCode = status
return this
}
setHeader(header, value) {
return (this.headers[header] = value)
}
setTimeout(timout) {
this.timout = timout
}
end(data, encoding) {
if (this.callback) {
return this.callback()
}
}
type(type) {
return (this.type = type)
}
}
MockResponse.initClass()
module.exports = MockResponse
| overleaf/web/test/unit/src/helpers/MockResponse.js/0 | {
"file_path": "overleaf/web/test/unit/src/helpers/MockResponse.js",
"repo_id": "overleaf",
"token_count": 1184
} | 567 |
/* eslint-disable
max-len,
no-return-assign,
no-unused-vars,
*/
// TODO: This file was created by bulk-decaffeinate.
// Fix any style issues and re-enable lint.
/*
* decaffeinate suggestions:
* DS102: Remove unnecessary code created because of implicit returns
* Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
*/
const sinon = require('sinon')
const assertCalledWith = sinon.assert.calledWith
const { expect } = require('chai')
const modulePath = '../../../../app/src/infrastructure/ProxyManager'
const SandboxedModule = require('sandboxed-module')
const MockRequest = require('../helpers/MockRequest')
const MockResponse = require('../helpers/MockResponse')
describe('ProxyManager', function () {
beforeEach(function () {
this.settings = { proxyUrls: {} }
this.request = sinon.stub().returns({
on() {},
pipe() {},
})
this.proxyManager = SandboxedModule.require(modulePath, {
requires: {
'@overleaf/settings': this.settings,
request: this.request,
},
})
this.proxyPath = '/foo/bar'
this.req = new MockRequest()
this.res = new MockResponse()
return (this.next = sinon.stub())
})
describe('apply', function () {
it('applies all paths', function () {
this.router = { get: sinon.stub() }
this.settings.proxyUrls = {
'/foo/bar': '',
'/foo/:id': '',
}
this.proxyManager.apply(this.router)
sinon.assert.calledTwice(this.router.get)
assertCalledWith(this.router.get, '/foo/bar')
return assertCalledWith(this.router.get, '/foo/:id')
})
it('applies methods other than get', function () {
this.router = {
post: sinon.stub(),
put: sinon.stub(),
}
this.settings.proxyUrls = {
'/foo/bar': { options: { method: 'post' } },
'/foo/:id': { options: { method: 'put' } },
}
this.proxyManager.apply(this.router)
sinon.assert.calledOnce(this.router.post)
sinon.assert.calledOnce(this.router.put)
assertCalledWith(this.router.post, '/foo/bar')
return assertCalledWith(this.router.put, '/foo/:id')
})
})
describe('createProxy', function () {
beforeEach(function () {
this.req.url = this.proxyPath
this.req.route.path = this.proxyPath
this.req.query = {}
this.req.params = {}
this.req.headers = {}
return (this.settings.proxyUrls = {})
})
afterEach(function () {
this.next.reset()
return this.request.reset()
})
it('does not calls next when match', function () {
const target = '/'
this.settings.proxyUrls[this.proxyPath] = target
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
sinon.assert.notCalled(this.next)
return sinon.assert.called(this.request)
})
it('proxy full URL', function () {
const targetUrl = 'https://user:pass@foo.bar:123/pa/th.ext?query#hash'
this.settings.proxyUrls[this.proxyPath] = targetUrl
this.proxyManager.createProxy(targetUrl)(this.req)
return assertCalledWith(this.request, { url: targetUrl })
})
it('overwrite query', function () {
const targetUrl = 'foo.bar/baz?query'
this.req.query = { requestQuery: 'important' }
this.settings.proxyUrls[this.proxyPath] = targetUrl
this.proxyManager.createProxy(targetUrl)(this.req)
const newTargetUrl = 'foo.bar/baz?requestQuery=important'
return assertCalledWith(this.request, { url: newTargetUrl })
})
it('handles target objects', function () {
const target = { baseUrl: 'api.v1', path: '/pa/th' }
this.settings.proxyUrls[this.proxyPath] = target
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
return assertCalledWith(this.request, { url: 'api.v1/pa/th' })
})
it('handles missing baseUrl', function () {
const target = { path: '/pa/th' }
this.settings.proxyUrls[this.proxyPath] = target
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
return assertCalledWith(this.request, { url: 'undefined/pa/th' })
})
it('handles dynamic path', function () {
const target = {
baseUrl: 'api.v1',
path(params) {
return `/resource/${params.id}`
},
}
this.settings.proxyUrls['/res/:id'] = target
this.req.url = '/res/123'
this.req.route.path = '/res/:id'
this.req.params = { id: 123 }
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
return assertCalledWith(this.request, { url: 'api.v1/resource/123' })
})
it('set arbitrary options on request', function () {
const target = {
baseUrl: 'api.v1',
path: '/foo',
options: { foo: 'bar' },
}
this.req.url = '/foo'
this.req.route.path = '/foo'
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
return assertCalledWith(this.request, {
foo: 'bar',
url: 'api.v1/foo',
})
})
it('passes cookies', function () {
const target = { baseUrl: 'api.v1', path: '/foo' }
this.req.url = '/foo'
this.req.route.path = '/foo'
this.req.headers = { cookie: 'cookie' }
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
return assertCalledWith(this.request, {
headers: {
Cookie: 'cookie',
},
url: 'api.v1/foo',
})
})
it('passes body for post', function () {
const target = {
baseUrl: 'api.v1',
path: '/foo',
options: { method: 'post' },
}
this.req.url = '/foo'
this.req.route.path = '/foo'
this.req.body = { foo: 'bar' }
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
return assertCalledWith(this.request, {
form: {
foo: 'bar',
},
method: 'post',
url: 'api.v1/foo',
})
})
it('passes body for put', function () {
const target = {
baseUrl: 'api.v1',
path: '/foo',
options: { method: 'put' },
}
this.req.url = '/foo'
this.req.route.path = '/foo'
this.req.body = { foo: 'bar' }
this.proxyManager.createProxy(target)(this.req, this.res, this.next)
return assertCalledWith(this.request, {
form: {
foo: 'bar',
},
method: 'put',
url: 'api.v1/foo',
})
})
})
})
| overleaf/web/test/unit/src/infrastructure/ProxyManagerTests.js/0 | {
"file_path": "overleaf/web/test/unit/src/infrastructure/ProxyManagerTests.js",
"repo_id": "overleaf",
"token_count": 2791
} | 568 |
{
"extends": [
"@ownclouders"
]
}
| owncloud/web/.eslintrc.json/0 | {
"file_path": "owncloud/web/.eslintrc.json",
"repo_id": "owncloud",
"token_count": 23
} | 569 |
Change: Removed favorite button from file list and added it in the sidebar
We've removed the favorite star button in the file list and added instead a functionality
to the before non-working star button in the file's sidebar. We also added a new action in
the file action dropdown menu which allows you to toggle the favorite status of your file.
https://github.com/owncloud/web/issues/1987
https://github.com/owncloud/web/pull/3336
| owncloud/web/changelog/0.10.0_2020-05-26/3336/0 | {
"file_path": "owncloud/web/changelog/0.10.0_2020-05-26/3336",
"repo_id": "owncloud",
"token_count": 108
} | 570 |
Change: Rework account dropdown
We've removed user avatar, user email and version from the account dropdown.
The log out button has been changed into a link.
All links in account dropdown are now inside of a list.
https://github.com/owncloud/product/issues/82
https://github.com/owncloud/web/pull/3605 | owncloud/web/changelog/0.11.0_2020-06-26/rework-account-dropdown/0 | {
"file_path": "owncloud/web/changelog/0.11.0_2020-06-26/rework-account-dropdown",
"repo_id": "owncloud",
"token_count": 83
} | 571 |
Bugfix: Fix navigation to the root folder from location picker
The target location in the location picker was appending a whitespace when trying to go to root folder.
This resulted in an error when trying to load such folder. We've removed the whitespace to fix the navigation.
https://github.com/owncloud/web/pull/3756 | owncloud/web/changelog/0.12.0_2020-07-10/location-picker-root-target/0 | {
"file_path": "owncloud/web/changelog/0.12.0_2020-07-10/location-picker-root-target",
"repo_id": "owncloud",
"token_count": 78
} | 572 |
Change: Adapt to new ocis-settings data model
ocis-settings introduced UUIDs and less verbose endpoint and message type names. This PR adjusts web accordingly.
https://github.com/owncloud/web/pull/3806
https://github.com/owncloud/owncloud-sdk/pull/520
https://github.com/owncloud/ocis-settings/pull/46
| owncloud/web/changelog/0.15.0_2020-08-19/adapt-to-settings-data-model.md/0 | {
"file_path": "owncloud/web/changelog/0.15.0_2020-08-19/adapt-to-settings-data-model.md",
"repo_id": "owncloud",
"token_count": 93
} | 573 |
Change: Change sharing wording
Renamed "Share" action to "Add people" and header column in the shared with list from "People" to "Shared with".
https://github.com/owncloud/web/pull/4120
| owncloud/web/changelog/0.18.0_2020-10-05/change-share-to-add-people/0 | {
"file_path": "owncloud/web/changelog/0.18.0_2020-10-05/change-share-to-add-people",
"repo_id": "owncloud",
"token_count": 54
} | 574 |
Bugfix: Fix browse to files page in the ui tests
When the ui tests where executing the "the user has browsed to the files page" step then it wouldn't wait until the files were loaded.
https://github.com/owncloud/web/issues/4281
| owncloud/web/changelog/0.24.0_2020-11-06/fix-browse-to-files-page/0 | {
"file_path": "owncloud/web/changelog/0.24.0_2020-11-06/fix-browse-to-files-page",
"repo_id": "owncloud",
"token_count": 65
} | 575 |
Bugfix: Don't break file/folder names in text editor
The label in the text editor that displays the path of the active file was removing the first character instead of trimming leading slashes. This might have lead to situations where actual characters were removed. We fixed this by only removing leading slashes instead of blindly removing the first character.
https://github.com/owncloud/web/pull/4391
| owncloud/web/changelog/0.28.0_2020-12-04/text-editor-file-path-label/0 | {
"file_path": "owncloud/web/changelog/0.28.0_2020-12-04/text-editor-file-path-label",
"repo_id": "owncloud",
"token_count": 89
} | 576 |
Enhancement: Add empty folder message in file list views
Whenever a folder contains no entries in any of the file list views,
a message is now shown indicating that the folder is empty, or that there are no favorites, etc.
https://github.com/owncloud/web/issues/1910
https://github.com/owncloud/web/pull/2975
| owncloud/web/changelog/0.4.0_2020-02-14/1910/0 | {
"file_path": "owncloud/web/changelog/0.4.0_2020-02-14/1910",
"repo_id": "owncloud",
"token_count": 84
} | 577 |
Bugfix: Fix console warning about search query in public page
Fixed console warning about the search query attribute not being available
whenever the search fields are not visible, for example when
accessing a public link page.
https://github.com/owncloud/web/pull/3041
| owncloud/web/changelog/0.5.0_2020-03-02/3041/0 | {
"file_path": "owncloud/web/changelog/0.5.0_2020-03-02/3041",
"repo_id": "owncloud",
"token_count": 64
} | 578 |
Bugfix: Fix logout when no tokens are known anymore
Single Log Out requires the id_token and in cases where this token is no
longer known calling the SLO endpoint will result in an error.
This has been fixed.
https://github.com/owncloud/web/pull/2961
| owncloud/web/changelog/0.7.0_2020-03-30/2961/0 | {
"file_path": "owncloud/web/changelog/0.7.0_2020-03-30/2961",
"repo_id": "owncloud",
"token_count": 70
} | 579 |
Bugfix: Fix translation message extraction from plain javascript files
https://github.com/owncloud/web/pull/3346
https://github.com/Polyconseil/easygettext/issues/81
| owncloud/web/changelog/0.9.0_2020-04-27/3346/0 | {
"file_path": "owncloud/web/changelog/0.9.0_2020-04-27/3346",
"repo_id": "owncloud",
"token_count": 48
} | 580 |
Enhancement: Update ODS to 2.0.3
We've updated the ownCloud design system to version 2.0.3.
https://github.com/owncloud/owncloud-design-system/releases/tag/v2.0.3
https://github.com/owncloud/web/pull/4488
| owncloud/web/changelog/1.0.0_2020-12-16/update-ods-2.0.3/0 | {
"file_path": "owncloud/web/changelog/1.0.0_2020-12-16/update-ods-2.0.3",
"repo_id": "owncloud",
"token_count": 77
} | 581 |
Enhancement: A11y improvements for meta attributes
For a11y the html language attribute will be set dynamically <html lang="xx"/>.
For a11y the title will be set automatically following the schema:
sub item (e.G file) - route (e.g All Files) - general name (e.g ownCloud)
https://github.com/owncloud/web/issues/4342
https://github.com/owncloud/web/issues/4338
https://github.com/owncloud/web/pull/4811
| owncloud/web/changelog/2.1.0_2021-03-24/enhancement-a11y-improvements-for-meta-attributes/0 | {
"file_path": "owncloud/web/changelog/2.1.0_2021-03-24/enhancement-a11y-improvements-for-meta-attributes",
"repo_id": "owncloud",
"token_count": 125
} | 582 |
Enhancement: Use ODS translations
Some ODS components were using their own translation strings which were available in the ODS but
not exported there/imported in the web project. Now, we import the translation strings from the ODS package
and merge them with the web translations.
https://github.com/owncloud/web/pull/4934
| owncloud/web/changelog/3.0.0_2021-04-21/enhancement-use-ods-translations/0 | {
"file_path": "owncloud/web/changelog/3.0.0_2021-04-21/enhancement-use-ods-translations",
"repo_id": "owncloud",
"token_count": 79
} | 583 |
Bugfix: Correct sharee tag
The tag _inside_ a shared folder always announced the current user as "owner",
since the shares lookup didn't check for the parent folders' ownership. This has
been fixed now and users get the correct tag (e.g. "Viewer", "Editor" etc) in the sidebar.
https://github.com/owncloud/web/pull/5112
| owncloud/web/changelog/3.2.0_2021-05-31/bugfix-sharee-tag/0 | {
"file_path": "owncloud/web/changelog/3.2.0_2021-05-31/bugfix-sharee-tag",
"repo_id": "owncloud",
"token_count": 91
} | 584 |
Bugfix: show `0` as used quota if a negative number is given
In the case if the server returns a negative number as used quota (what should not happen) show `0 B of 2 GB` and not only of ` 2 GB`
https://github.com/owncloud/web/pull/5229
| owncloud/web/changelog/3.3.0_2021-06-23/bugfix-show-0-when-negative-quota-given/0 | {
"file_path": "owncloud/web/changelog/3.3.0_2021-06-23/bugfix-show-0-when-negative-quota-given",
"repo_id": "owncloud",
"token_count": 71
} | 585 |
Enhancement: Improve accessibility for the files sidebar
We've did several improvements to enhance the accessibility on the files sidebar:
- Transformed the file name to a h2 element
- Transformed the "Open folder"-action to a link instead of a button
- Transformed the favorite-star to a button-element
- Adjusted aria-label of the favorite-star to describe what it does instead of its current state
- Added a more descriptive close button label
- Clicking outside of the sidebar now closes it
- Removed the aria-label on the action buttons as they already include proper labels
- Added a hint for screen readers if an action opens a new window/tab
- Make sidebar header sticky
https://github.com/owncloud/web/pull/5000
https://github.com/owncloud/web/pull/5266
| owncloud/web/changelog/3.3.0_2021-06-23/enhancement-files-sidebar-accessibility/0 | {
"file_path": "owncloud/web/changelog/3.3.0_2021-06-23/enhancement-files-sidebar-accessibility",
"repo_id": "owncloud",
"token_count": 184
} | 586 |
Enhancement: Add focus trap to left sidebar
We've added a focus trap to the left sidebar on smaller resolutions when it's collapsible.
If the sidebar is opened and focused, the focus stays within the sidebar.
https://github.com/owncloud/web/pull/5027
| owncloud/web/changelog/3.3.0_2021-06-23/enhancement-sidebar-focus-trap/0 | {
"file_path": "owncloud/web/changelog/3.3.0_2021-06-23/enhancement-sidebar-focus-trap",
"repo_id": "owncloud",
"token_count": 65
} | 587 |
Bugfix: Load preview in right sidebar
We fixed a bug that caused previews not being loaded in the details accordion of the right sidebar.
https://github.com/owncloud/web/pull/5501
| owncloud/web/changelog/3.4.1_2021-07-12/bugfix-details-preview/0 | {
"file_path": "owncloud/web/changelog/3.4.1_2021-07-12/bugfix-details-preview",
"repo_id": "owncloud",
"token_count": 48
} | 588 |
Enhancement: Sidebar sliding panels navigation
The sidebar now uses a ios like concept for navigate through the different actions in the sidebar.
It replaces the accordion navigation entirely.
https://github.com/owncloud/web/pull/5549
https://github.com/owncloud/web/issues/5523 | owncloud/web/changelog/4.0.0_2021-08-04/enhancement-sidebar-navigation/0 | {
"file_path": "owncloud/web/changelog/4.0.0_2021-08-04/enhancement-sidebar-navigation",
"repo_id": "owncloud",
"token_count": 72
} | 589 |
Enhancement: Show sharees as collapsed list of avatars
We've introduced a collapsed list of avatars of sharees in the `People` panel of the right sidebar.
On click we switch to showing the full list of sharees. With this additional intermediate state we
were able to clean up the UI a bit for easier cognitive load.
https://github.com/owncloud/web/pull/5758
https://github.com/owncloud/web/issues/5736
| owncloud/web/changelog/4.2.0_2021-09-14/enhancement-show-sharees-as-avatars/0 | {
"file_path": "owncloud/web/changelog/4.2.0_2021-09-14/enhancement-show-sharees-as-avatars",
"repo_id": "owncloud",
"token_count": 107
} | 590 |
Bugfix: Clean router path handling
This patch was already introduced earlier for the files application only.
In the meantime we found out that this is also needed on different places across the ecosystem.
We've refactored the way how the patch gets applied to the routes: It is now possible to set an individual route's `meta.patchCleanPath` to true.
https://github.com/owncloud/web/pull/5894
https://github.com/owncloud/web/issues/4595#issuecomment-938587035
| owncloud/web/changelog/4.4.0_2021-10-26/bugfix-router-clean-path/0 | {
"file_path": "owncloud/web/changelog/4.4.0_2021-10-26/bugfix-router-clean-path",
"repo_id": "owncloud",
"token_count": 121
} | 591 |
Enhancement: App provider and archiver on public links
We made the app provider and archiver services available on public links. As a prerequisite for this we needed to make backend capabilities available on public links, which will
be beneficial for all future extension development.
https://github.com/owncloud/web/pull/5924
https://github.com/owncloud/web/issues/5884
https://github.com/owncloud/ocis/issues/2479
https://github.com/owncloud/web/issues/2479
https://github.com/owncloud/web/issues/5901
| owncloud/web/changelog/4.5.0_2021-11-16/enhancement-public-link-capabilities/0 | {
"file_path": "owncloud/web/changelog/4.5.0_2021-11-16/enhancement-public-link-capabilities",
"repo_id": "owncloud",
"token_count": 138
} | 592 |
Bugfix: Open in browser for public files
We fixed opening publicly shared files in the browser.
https://github.com/owncloud/web/issues/4615
https://github.com/owncloud/web/pull/6133
| owncloud/web/changelog/4.7.0_2021-12-16/bugfix-open-in-browser-on-public-files/0 | {
"file_path": "owncloud/web/changelog/4.7.0_2021-12-16/bugfix-open-in-browser-on-public-files",
"repo_id": "owncloud",
"token_count": 55
} | 593 |
Enhancement: Print version numbers
The package version of the web UI and the version of the backend (if available) now get printed to the browser console and get set as meta generator tag in the html head. This makes it possible to easily reference versions in bug reports.
https://github.com/owncloud/web/issues/5954
https://github.com/owncloud/web/pull/6190
| owncloud/web/changelog/4.9.0_2021-12-24/enhancement-print-version/0 | {
"file_path": "owncloud/web/changelog/4.9.0_2021-12-24/enhancement-print-version",
"repo_id": "owncloud",
"token_count": 91
} | 594 |
Enhancement: File creation via app provider
For oCIS deployments the integration of the app provider for editing files was enhanced by adding support for the app provider capabilities to create files as well.
https://github.com/owncloud/web/pull/5890
https://github.com/owncloud/web/pull/6312
| owncloud/web/changelog/5.0.0_2022-02-14/enhancement-app-provider-create-files/0 | {
"file_path": "owncloud/web/changelog/5.0.0_2022-02-14/enhancement-app-provider-create-files",
"repo_id": "owncloud",
"token_count": 75
} | 595 |
Enhancement: Implement spaces front page
Each space can now be entered from within the spaces list. The space front page will then display all the space contents, plus an image and a readme file if set. Basic actions like uploading files, creating folders, renaming resources, and more. were also implemented in the course of this.
https://github.com/owncloud/web/pull/6287
https://github.com/owncloud/web/issues/6271
| owncloud/web/changelog/5.0.0_2022-02-14/enhancement-spaces-front-page/0 | {
"file_path": "owncloud/web/changelog/5.0.0_2022-02-14/enhancement-spaces-front-page",
"repo_id": "owncloud",
"token_count": 104
} | 596 |
Bugfix: Resize observer errors within subfolders of a space
We've fixed a bug where the resize observer crashes within subfolders of a space because there is no element to observe.
https://github.com/owncloud/web/pull/6569
| owncloud/web/changelog/5.3.0_2022-03-23/bugfix-resize-observer-errors/0 | {
"file_path": "owncloud/web/changelog/5.3.0_2022-03-23/bugfix-resize-observer-errors",
"repo_id": "owncloud",
"token_count": 59
} | 597 |
Enhancement: Move share indicators
We've moved the share/status indicators into a separate column
and adjusted the design in ODS.
https://github.com/owncloud/web/issues/5976
https://github.com/owncloud/web/pull/6552
https://github.com/owncloud/owncloud-design-system/pull/2014
https://github.com/owncloud/web/pull/6583
| owncloud/web/changelog/5.3.0_2022-03-23/enhancement-move-share-indicators/0 | {
"file_path": "owncloud/web/changelog/5.3.0_2022-03-23/enhancement-move-share-indicators",
"repo_id": "owncloud",
"token_count": 100
} | 598 |
Enhancement: Update ODS to v13.0.0
We updated the ownCloud Design System to version 13.0.0. Please refer to the full changelog in the ODS release (linked) for more details. Summary:
- Change - Default type of OcButton: https://github.com/owncloud/owncloud-design-system/pull/2009
- Change - Remove OcStatusIndicators from OcResource: https://github.com/owncloud/owncloud-design-system/pull/2014
- Enhancement - Redesign OcStatusIndicators: https://github.com/owncloud/owncloud-design-system/pull/2014
- Enhancement - Icons for drawio, ifc and odg resource types: https://github.com/owncloud/owncloud-design-system/pull/2005
- Enhancement - Apply size property to oc-tag: https://github.com/owncloud/owncloud-design-system/pull/2011
- Enhancement - Underline OcResourceName: https://github.com/owncloud/owncloud-design-system/pull/2019
- Enhancement - Configurable OcResource parentfolder name: https://github.com/owncloud/owncloud-design-system/pull/2029
- Enhancement - Polish OcSwitch: https://github.com/owncloud/owncloud-design-system/pull/2018
- Enhancement - Make filled primary OcButton use gradient background: https://github.com/owncloud/owncloud-design-system/pull/2036
- Bugfix - Disabled OcSelect background: https://github.com/owncloud/owncloud-design-system/pull/2008
- Bugfix - Icons/Thumbnails were only visible for clickable resources: https://github.com/owncloud/owncloud-design-system/pull/2007
- Bugfix - OcSelect transparent background: https://github.com/owncloud/owncloud-design-system/pull/2036
https://github.com/owncloud/web/pull/6540
https://github.com/owncloud/web/pull/6600
https://github.com/owncloud/web/pull/6584
https://github.com/owncloud/web/pull/6561
https://github.com/owncloud/owncloud-design-system/releases/tag/v13.0.0
| owncloud/web/changelog/5.3.0_2022-03-23/enhancement-update-ods/0 | {
"file_path": "owncloud/web/changelog/5.3.0_2022-03-23/enhancement-update-ods",
"repo_id": "owncloud",
"token_count": 536
} | 599 |
Enhancement: Audio handling in preview app
We've built audio preview support for flac, mp3, ogg and wav files into the preview app.
https://github.com/owncloud/web/pull/6514
| owncloud/web/changelog/5.4.0_2022-04-11/enhancement-preview-mimetypes/0 | {
"file_path": "owncloud/web/changelog/5.4.0_2022-04-11/enhancement-preview-mimetypes",
"repo_id": "owncloud",
"token_count": 53
} | 600 |
Bugfix: Apply text selection range for new files
We've fixed a bug, where the text selection range for a new file has not been applied only for the file name but also
for the file extension.
This is now working as in the rename modal and just selects the text for the file name.
https://github.com/owncloud/web/issues/6756
https://github.com/owncloud/web/pull/6803
| owncloud/web/changelog/5.5.0_2022-06-20/bugfix-apply-text-selection-range-for-new-files/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/bugfix-apply-text-selection-range-for-new-files",
"repo_id": "owncloud",
"token_count": 99
} | 601 |
Bugfix: Require quick link password if enforced in ownCloud 10
We've fixed a bug, where no password was requested while creating a quick link,
this led to a silent error where no quick link was created.
We now prompt for a quick link password if enforced
https://github.com/owncloud/web/pull/6967
https://github.com/owncloud/web/issues/6963
| owncloud/web/changelog/5.5.0_2022-06-20/bugfix-require-quick-link-password-if-enforced-in-oC10/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/bugfix-require-quick-link-password-if-enforced-in-oC10",
"repo_id": "owncloud",
"token_count": 92
} | 602 |
Bugfix: The selected app item has a bad text color contrast in light mode
We've fixed the contrast of the text color for hovered and active application menus items.
https://github.com/owncloud/web/pull/6954
https://github.com/owncloud/web/issues/6958
| owncloud/web/changelog/5.5.0_2022-06-20/bugfix-text-color-application-menu-item/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/bugfix-text-color-application-menu-item",
"repo_id": "owncloud",
"token_count": 70
} | 603 |
Enhancement: Copy/Move conflict dialog
We've added a conflict dialog for moving resources via drag&drop in the files list
https://github.com/owncloud/web/pull/7119
https://github.com/owncloud/web/pull/6994
https://github.com/owncloud/web/pull/7151
https://github.com/owncloud/web/issues/6996
| owncloud/web/changelog/5.5.0_2022-06-20/enhancement-copy-move-conflict-dialog/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/enhancement-copy-move-conflict-dialog",
"repo_id": "owncloud",
"token_count": 94
} | 604 |
Enhancement: Log correct oCIS version if available
oCIS has introduced a new `productversion` field to announce it's correct version while maintaining a fake 10.x.x version in the `versionstring` field to keep clients compatible. We're using the new productversion field when it exists and use versionstring as a fallback. Thus the backend product information prints the correct oCIS version now.
https://github.com/owncloud/ocis/pull/3805
https://github.com/owncloud/web/pull/7045
| owncloud/web/changelog/5.5.0_2022-06-20/enhancement-productversion-log/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/enhancement-productversion-log",
"repo_id": "owncloud",
"token_count": 123
} | 605 |
Enhancement: Upload data during creation
Uploading via tus now uses the `uploadDataDuringCreation` option which saves up one request.
https://github.com/owncloud/web/pull/7111
https://github.com/owncloud/web/issues/7066
| owncloud/web/changelog/5.5.0_2022-06-20/enhancement-upload-data-during-creation/0 | {
"file_path": "owncloud/web/changelog/5.5.0_2022-06-20/enhancement-upload-data-during-creation",
"repo_id": "owncloud",
"token_count": 66
} | 606 |
Bugfix: Default to user context
We've fixed a bug where routes without explicit `auth` requirement (i.e. user context) and without any context route in the URL were recognized as neither user-context nor public-link-context. In such situations we now expect that the session requires a user and redirect to the login page.
https://github.com/owncloud/web/pull/7437
| owncloud/web/changelog/5.7.0_2022-09-09/bugfix-default-to-user-context/0 | {
"file_path": "owncloud/web/changelog/5.7.0_2022-09-09/bugfix-default-to-user-context",
"repo_id": "owncloud",
"token_count": 89
} | 607 |
Bugfix: Link indicator on "Shared via link"-page
We've fixed the icon and the sidebar for the link indicator on the "Shared via link"-page.
https://github.com/owncloud/web/pull/7355
https://github.com/owncloud/web/issues/7345
| owncloud/web/changelog/5.7.0_2022-09-09/bugfix-link-indicator-shared-via-link-page/0 | {
"file_path": "owncloud/web/changelog/5.7.0_2022-09-09/bugfix-link-indicator-shared-via-link-page",
"repo_id": "owncloud",
"token_count": 71
} | 608 |
Bugfix: Print backend version
We fixed a regression with printing version information to the browser console (the backend version was not showing up anymore). Since loading the public link / user context is blocking the boot process of applications after a [recent PR](https://github.com/owncloud/web/pull/7072) has been merged, we are now able to reliably print the backend version on the first page load after login as well (was not possible before).
https://github.com/owncloud/web/issues/7272
https://github.com/owncloud/web/pull/7284
| owncloud/web/changelog/5.7.0_2022-09-09/bugfix-print-backend-version/0 | {
"file_path": "owncloud/web/changelog/5.7.0_2022-09-09/bugfix-print-backend-version",
"repo_id": "owncloud",
"token_count": 130
} | 609 |
Bugfix: Space sidebar sharing indicators
We have fixed the way the sharing indicators for space members and link shares were displayed in the details panel of the sidebar as well as the click behavior for accessing the shares panel through the sharing information.
https://github.com/owncloud/web/pull/6921
https://github.com/owncloud/web/issues/6917
| owncloud/web/changelog/5.7.0_2022-09-09/bugfix-space-sidebar-sharingindicators/0 | {
"file_path": "owncloud/web/changelog/5.7.0_2022-09-09/bugfix-space-sidebar-sharingindicators",
"repo_id": "owncloud",
"token_count": 82
} | 610 |
Enhancement: Adjust helper texts
https://github.com/owncloud/web/pull/7404
https://github.com/owncloud/web/issues/7331
| owncloud/web/changelog/5.7.0_2022-09-09/enhancement-adjust-helper-texts/0 | {
"file_path": "owncloud/web/changelog/5.7.0_2022-09-09/enhancement-adjust-helper-texts",
"repo_id": "owncloud",
"token_count": 41
} | 611 |
Enhancement: Remember the UI that was last selected via the application switcher
With this change, ownCloud will remember the UI that was last selected via the application switcher. This only works when using ownCloud 10 as backend.
https://github.com/owncloud/web/pull/6173
https://github.com/owncloud/enterprise/issues/4694
| owncloud/web/changelog/5.7.0_2022-09-09/enhancement-remember-selected-ui/0 | {
"file_path": "owncloud/web/changelog/5.7.0_2022-09-09/enhancement-remember-selected-ui",
"repo_id": "owncloud",
"token_count": 84
} | 612 |
Enhancement: Update Uppy to v3.0.1
We've updated Uppy to v3.0.1. This allows us to enable the `creation-with-upload` extension, which saves up one request per file during upload.
https://github.com/owncloud/web/issues/7177
https://github.com/owncloud/web/pull/7515
| owncloud/web/changelog/5.7.0_2022-09-09/enhancement-update-uppy/0 | {
"file_path": "owncloud/web/changelog/5.7.0_2022-09-09/enhancement-update-uppy",
"repo_id": "owncloud",
"token_count": 88
} | 613 |
Bugfix: Prevent file upload when folder creation failed
We've fixed a bug where files would try to be uploaded if the creation of their respective folder failed beforehand.
https://github.com/owncloud/web/pull/7975
https://github.com/owncloud/web/pull/7999
https://github.com/owncloud/web/issues/7957
| owncloud/web/changelog/6.0.0_2022-11-29/bugfix-file-upload-with-failed-folder-creation/0 | {
"file_path": "owncloud/web/changelog/6.0.0_2022-11-29/bugfix-file-upload-with-failed-folder-creation",
"repo_id": "owncloud",
"token_count": 84
} | 614 |
Bugfix: Remove the "close sidebar"-calls on delete
We've removed the "close sidebar"-calls when deleting a resource as the mutations are not available as well as not needed anymore.
https://github.com/owncloud/web/issues/7699
https://github.com/owncloud/web/pull/7733
| owncloud/web/changelog/6.0.0_2022-11-29/bugfix-remove-close-sidebar-calls-on-delete/0 | {
"file_path": "owncloud/web/changelog/6.0.0_2022-11-29/bugfix-remove-close-sidebar-calls-on-delete",
"repo_id": "owncloud",
"token_count": 76
} | 615 |
Bugfix: Trash bin sidebar
We've fixed the sidebar in the trash bin which was throwing errors and not showing the right content.
https://github.com/owncloud/web/issues/7778
https://github.com/owncloud/web/pull/7787
| owncloud/web/changelog/6.0.0_2022-11-29/bugfix-trash-bin-sidebar/0 | {
"file_path": "owncloud/web/changelog/6.0.0_2022-11-29/bugfix-trash-bin-sidebar",
"repo_id": "owncloud",
"token_count": 62
} | 616 |
Enhancement: Disable share renaming
Renaming of shares has been disabled temporarily until it works as expected.
https://github.com/owncloud/web/pull/7865
| owncloud/web/changelog/6.0.0_2022-11-29/enhancement-disable-share-renaming/0 | {
"file_path": "owncloud/web/changelog/6.0.0_2022-11-29/enhancement-disable-share-renaming",
"repo_id": "owncloud",
"token_count": 42
} | 617 |
Bugfix: Batch context actions in admin settings
Several issues when triggering batch actions via the context menu for users/groups/spaces in the admin-settings have been fixed. Some actions were showing wrongly ("edit"), some actions were resetting the current selection ("show details").
https://github.com/owncloud/web/issues/8549
https://github.com/owncloud/web/pull/8785
| owncloud/web/changelog/7.0.0_2023-06-02/bugfix-admin-settings-batch-context-actions/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/bugfix-admin-settings-batch-context-actions",
"repo_id": "owncloud",
"token_count": 92
} | 618 |
Bugfix: Group members sorting
Sorting groups by their member count has been fixed.
https://github.com/owncloud/web/issues/8592
https://github.com/owncloud/web/pull/8600
| owncloud/web/changelog/7.0.0_2023-06-02/bugfix-group-members-sorting/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/bugfix-group-members-sorting",
"repo_id": "owncloud",
"token_count": 53
} | 619 |
Bugfix: password enforced check for public links
We've fixed a bug where we ignored the selected role in the password enforcement check. The web ui was sending the request to update a link instead of showing a modal with a password input prompt.
https://github.com/owncloud/web/issues/8587
https://github.com/owncloud/web/pull/8623
https://github.com/owncloud/web/pull/8745
| owncloud/web/changelog/7.0.0_2023-06-02/bugfix-password-enforced-check/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/bugfix-password-enforced-check",
"repo_id": "owncloud",
"token_count": 102
} | 620 |
Bugfix: Search repeating no results message
We've fixed a bug that caused to repeat the 'no results' message when searching.
https://github.com/owncloud/web/issues/8054
https://github.com/owncloud/web/pull/8062 | owncloud/web/changelog/7.0.0_2023-06-02/bugfix-search-repeating-no-results-message/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/bugfix-search-repeating-no-results-message",
"repo_id": "owncloud",
"token_count": 61
} | 621 |
Bugfix: Incorrect pause state in upload info
An incorrect pause state in the upload info modal has been fixed.
https://github.com/owncloud/web/issues/9080
https://github.com/owncloud/web/pull/9141
| owncloud/web/changelog/7.0.0_2023-06-02/bugfix-upload-info-incorrect-pause/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/bugfix-upload-info-incorrect-pause",
"repo_id": "owncloud",
"token_count": 60
} | 622 |
Enhancement: Adjust missing reshare permissions message
We've changed the missing reshare permission message to be more clear.
https://github.com/owncloud/web/pull/8820
https://github.com/owncloud/web/issues/8701
| owncloud/web/changelog/7.0.0_2023-06-02/enhancement-adjust-no-reshare-perm-message/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/enhancement-adjust-no-reshare-perm-message",
"repo_id": "owncloud",
"token_count": 60
} | 623 |
Enhancement: Context helper read more link configurable
We've added a configuration variable to disable the read more link in the contextual helper.
https://github.com/owncloud/web/pull/8713
https://github.com/owncloud/web/pull/8719
https://github.com/owncloud/web/issues/8570
| owncloud/web/changelog/7.0.0_2023-06-02/enhancement-context-helper-read-more-configurable/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/enhancement-context-helper-read-more-configurable",
"repo_id": "owncloud",
"token_count": 80
} | 624 |
Enhancement: Remove placeholder, add customizable label
The formerly fixed placeholder for the text input on item filter component got removed.
Also, we added a customizable label.
https://github.com/owncloud/web/pull/8711
| owncloud/web/changelog/7.0.0_2023-06-02/enhancement-itemfilter-remove-placeholder-add-customizable-label/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/enhancement-itemfilter-remove-placeholder-add-customizable-label",
"repo_id": "owncloud",
"token_count": 54
} | 625 |
Enhancement: Beautify file version list
We added css changes to the file versions list to make it look more clean and
to use standardized layouts like action buttons, download icons etc.
https://github.com/owncloud/web/issues/8503
https://github.com/owncloud/web/pull/8504
| owncloud/web/changelog/7.0.0_2023-06-02/enhancement-re-style-file-versions/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/enhancement-re-style-file-versions",
"repo_id": "owncloud",
"token_count": 75
} | 626 |
Enhancement: Space member expiration
Space member shares now support expiration.
https://github.com/owncloud/web/pull/8320
https://github.com/owncloud/web/pull/8482
https://github.com/owncloud/web/issues/8328
| owncloud/web/changelog/7.0.0_2023-06-02/enhancement-space-member-expiration/0 | {
"file_path": "owncloud/web/changelog/7.0.0_2023-06-02/enhancement-space-member-expiration",
"repo_id": "owncloud",
"token_count": 66
} | 627 |
Bugfix: Authenticated public links breaking uploads
Opening public links in an authenticated context no longer breaks uploading resources.
https://github.com/owncloud/web/pull/9299
https://github.com/owncloud/web/issues/9298
| owncloud/web/changelog/7.1.0_2023-08-23/bugfix-authenticated-public-links-breaking-uploads/0 | {
"file_path": "owncloud/web/changelog/7.1.0_2023-08-23/bugfix-authenticated-public-links-breaking-uploads",
"repo_id": "owncloud",
"token_count": 59
} | 628 |
Enhancement: Add pagination options to admin settings
We've added pagination options to the admin settings app,
furthermore we've added more granular pagination options to the files app.
https://github.com/owncloud/web/pull/9199
https://github.com/owncloud/web/issues/9188
| owncloud/web/changelog/7.1.0_2023-08-23/enhancement-add-pagination-options-to-admin-settings/0 | {
"file_path": "owncloud/web/changelog/7.1.0_2023-08-23/enhancement-add-pagination-options-to-admin-settings",
"repo_id": "owncloud",
"token_count": 77
} | 629 |
Enhancement: Project spaces list viewmode
We've added a viewmode switcher to the project spaces overview with an additional list viewmode.
https://github.com/owncloud/web/pull/9195
https://github.com/owncloud/web/issues/9204
| owncloud/web/changelog/7.1.0_2023-08-23/enhancement-project-spaces-list-viewmode/0 | {
"file_path": "owncloud/web/changelog/7.1.0_2023-08-23/enhancement-project-spaces-list-viewmode",
"repo_id": "owncloud",
"token_count": 65
} | 630 |
Bugfix: Resolving external URLs
Resolving external URLs when only the file ID is given has been fixed.
https://github.com/owncloud/web/issues/9804
https://github.com/owncloud/web/pull/9833
| owncloud/web/changelog/7.1.1_2023-10-25/bugfix-external-url-resolving/0 | {
"file_path": "owncloud/web/changelog/7.1.1_2023-10-25/bugfix-external-url-resolving",
"repo_id": "owncloud",
"token_count": 58
} | 631 |
Bugfix: GDPR export polling
Periodically checking for a processed GDPR export in the account menu has been fixed.
https://github.com/owncloud/web/pull/10158
https://github.com/owncloud/web/issues/8862
| owncloud/web/changelog/8.0.0_2024-03-08/bugfix-gdpr-export-polling/0 | {
"file_path": "owncloud/web/changelog/8.0.0_2024-03-08/bugfix-gdpr-export-polling",
"repo_id": "owncloud",
"token_count": 61
} | 632 |
Bugfix: Respect the open-in-new-tab-config for external apps
The `WEB_OPTION_OPEN_APPS_IN_TAB` is now being respected correctly when opening files with external apps.
https://github.com/owncloud/web/pull/9663
https://github.com/owncloud/web/issues/9630
| owncloud/web/changelog/8.0.0_2024-03-08/bugfix-respect-new-tab-config-for-external-apps/0 | {
"file_path": "owncloud/web/changelog/8.0.0_2024-03-08/bugfix-respect-new-tab-config-for-external-apps",
"repo_id": "owncloud",
"token_count": 84
} | 633 |
Bugfix: Wrong share permissions when resharing off
We've fixed a bug where a share with custom permissions always sent the resharing bit although resharing was disabled.
https://github.com/owncloud/web/pull/10489
| owncloud/web/changelog/8.0.0_2024-03-08/bugfix-wrong-share-permissions/0 | {
"file_path": "owncloud/web/changelog/8.0.0_2024-03-08/bugfix-wrong-share-permissions",
"repo_id": "owncloud",
"token_count": 53
} | 634 |
Enhancement: Create link modal
When creating a link while passwords are enfoced, Web will now display a modal that lets the user not only set a password, but also the role and an optional expiration date.
https://github.com/owncloud/web/pull/10104
https://github.com/owncloud/web/pull/10145
https://github.com/owncloud/web/pull/10159
https://github.com/owncloud/web/pull/10187
https://github.com/owncloud/web/pull/10194
https://github.com/owncloud/web/issues/10157
| owncloud/web/changelog/8.0.0_2024-03-08/enhancement-create-link-modal/0 | {
"file_path": "owncloud/web/changelog/8.0.0_2024-03-08/enhancement-create-link-modal",
"repo_id": "owncloud",
"token_count": 147
} | 635 |
Enhancement: Handle postprocessing state via Server Sent Events
We've added the functionality to listen for events from the server that update the postprocessing state,
this allows the user to see if the postprocessing on a file is finished, without reloading the UI.
https://github.com/owncloud/web/pull/9771
https://github.com/owncloud/web/issues/9769
| owncloud/web/changelog/8.0.0_2024-03-08/enhancement-handle-postprocessing-state-via-sse/0 | {
"file_path": "owncloud/web/changelog/8.0.0_2024-03-08/enhancement-handle-postprocessing-state-via-sse",
"repo_id": "owncloud",
"token_count": 90
} | 636 |
Enhancement: Search tags filter chips style aligned
We've aligned the style of tags filter in search with the tags panel redesign.
https://github.com/owncloud/web/pull/9864
https://github.com/owncloud/web/issues/9834
| owncloud/web/changelog/8.0.0_2024-03-08/enhancement-search-tags-filter-style/0 | {
"file_path": "owncloud/web/changelog/8.0.0_2024-03-08/enhancement-search-tags-filter-style",
"repo_id": "owncloud",
"token_count": 62
} | 637 |
Enhancement: New WebDAV implementation in web-client
The WebDAV implementation of the ownCloudSDK has been deprecated in favor of a new implementation in the `web-client` package. For developers this means that every WebDAV request should be made using the WebDAV factory provided by the `ClientService`. E.g. to retrieve files: `const files = await clientService.webdav.listFiles(space)`.
https://github.com/owncloud/web/issues/9709
https://github.com/owncloud/web/pull/9764
| owncloud/web/changelog/8.0.0_2024-03-08/enhancement-web-client-dav-implementation/0 | {
"file_path": "owncloud/web/changelog/8.0.0_2024-03-08/enhancement-web-client-dav-implementation",
"repo_id": "owncloud",
"token_count": 130
} | 638 |
Change: Remove ocs user
BREAKING CHANGE for developers: The user from the ocs api has been removed in favor of the graph user. That means the user that can be retrieved from the store looks slightly different than the OCS user (though it still holds the same information).
For more details please see the linked PR down below.
https://github.com/owncloud/web/pull/10240
https://github.com/owncloud/web/issues/10210
| owncloud/web/changelog/9.0.0_2024-02-26/change-remove-ocs-user/0 | {
"file_path": "owncloud/web/changelog/9.0.0_2024-02-26/change-remove-ocs-user",
"repo_id": "owncloud",
"token_count": 107
} | 639 |
Enhancement: Tile sizes
We've adjusted the tile sizes to have a bigger base size and smaller stepping from one tile size to the next.
In addition to that the default tile size has been changed to the second stepping, so that initially both
space tiles and file/folder tiles have a sufficient size for reading longer names.
https://github.com/owncloud/web/issues/10018
https://github.com/owncloud/web/issues/10638
https://github.com/owncloud/web/pull/10558
https://github.com/owncloud/web/pull/10646
| owncloud/web/changelog/9.0.0_2024-02-26/enhancement-tile-sizes/0 | {
"file_path": "owncloud/web/changelog/9.0.0_2024-02-26/enhancement-tile-sizes",
"repo_id": "owncloud",
"token_count": 135
} | 640 |
---
title: "Conventions"
date: 2022-01-28T00:00:00+00:00
weight: 20
geekdocRepo: https://github.com/owncloud/web
geekdocEditPath: edit/master/docs/development
geekdocFilePath: conventions.md
---
{{< toc >}}
This is a collection of tips and conventions to follow when working on the [ownCloud web frontend](https://github.com/owncloud/web).
Since it is a living document, please open a PR if you find something missing.
## Contributing to ownCloud Web
Everyone is invited to contribute. Simply fork the [codebase](https://github.com/owncloud/web/),
check the [issues](https://github.com/owncloud/web/issues?q=is%3Aopen+is%3Aissue+label%3ATopic%3Agood-first-issue)
for a suitable one and open a pull request!
### Linting and Tests
To make sure your pull request can be efficiently reviewed and won't need a lot of changes down the road, please run the linter and
the unit tests via `pnpm lint --fix` and `pnpm test:unit` locally. Our [CI](https://drone.owncloud.com/owncloud/web) will run on
pull requests and report back any problems after that. For a further introduction on how we handle testing, please head to
the [testing docs]({{< ref "../testing/_index.md" >}}).
### Changelog Items
In our project, we follow [SemVer](https://semver.org/) and keep a changelog for every change that influences the user experience (where
"users" can be admins, end-users and developers).
Some changes, like refactoring, updating dependencies, writing documentation or adding tests don't require a changelog item.
Please add a changelog item to the `changelog/unreleased/` folder, referencing the issue and pull request numbers, following
the [changelog item template](https://github.com/owncloud/web/blob/master/changelog/TEMPLATE).
## Code Conventions
### Early Returns
We're trying to stick with early returns in our code to make it more performant and simpler to reason about it.
### Translations
Use the `v-text` directive in combination with `$gettext` (or a variation of it) inside HTML tags (instead of
a `<translate tag="h1">` or similar) in order to make reasoning about the DOM tree easier.
### TypeScript
We're using TypeScript, which allows us to catch bugs at transpile time. Clean types make sure our IDEs can support us
in reasoning about our (ever growing, complex) codebase.
### Vue 3 and Composition API
We've migrated from Vue 2 to Vue 3 late in 2022 and since then have been investing continuous efforts to move away from the Vue options API
in favor of the Vue composition API. The `web-pkg` helper package provides quite some composables which will help you in
app & extension development, so we encourage you to make use of the Vue composition API as well, even outside of the
ownCloud Web repository.
### Dependencies
To keep the bundle size small and reduce the risk of introducing security problems for our users, we try to limit
the amount of dependencies in our code base and keep them as up-to-date as possible.
| owncloud/web/docs/development/conventions.md/0 | {
"file_path": "owncloud/web/docs/development/conventions.md",
"repo_id": "owncloud",
"token_count": 816
} | 641 |
---
title: "Tests"
date: 2022-01-28T00:00:00+00:00
weight: 55
geekdocRepo: https://github.com/owncloud/web
geekdocEditPath: edit/master/docs/testing
geekdocFilePath: _index.md
geekdocCollapseSection: true
---
Guides on running different kinds of tests in ownCloud Web.
| owncloud/web/docs/testing/_index.md/0 | {
"file_path": "owncloud/web/docs/testing/_index.md",
"repo_id": "owncloud",
"token_count": 99
} | 642 |
const tinyColor = require('tinycolor2')
const { getPropType, sortProps, getPropCategory } = require('./utils')
module.exports = {
name: 'format/ods/json',
formatter: (dictionary) => {
const attributes = sortProps(dictionary.allProperties).reduce((acc, cur) => {
const prop = {
value: cur.value,
name: cur.name,
type: getPropType(cur),
category: getPropCategory(cur),
info: {}
}
if (prop.type === 'color') {
const color = tinyColor(cur.value)
prop.info.hex = color.toHexString()
prop.info.rgb = color.toRgbString()
prop.info.hsl = color.toHslString()
prop.info.hsv = color.toHsvString()
}
acc[cur.name] = prop
return acc
}, {})
const data = [
'{',
Object.keys(attributes)
.map((k) => ` "${k}": ${JSON.stringify(attributes[k])}`)
.join(',\n'),
'}'
].join('\n')
return data
}
}
| owncloud/web/packages/design-system/build/build-tokens/format-writer-json.js/0 | {
"file_path": "owncloud/web/packages/design-system/build/build-tokens/format-writer-json.js",
"repo_id": "owncloud",
"token_count": 445
} | 643 |
Bugfix: Fixed oc-icon to reload image when url changes
The oc-icon component will now reload its image whenever the url property has been modified
https://github.com/owncloud/owncloud-design-system/pull/681
| owncloud/web/packages/design-system/changelog/1.1.1_2020-03-18/681/0 | {
"file_path": "owncloud/web/packages/design-system/changelog/1.1.1_2020-03-18/681",
"repo_id": "owncloud",
"token_count": 56
} | 644 |
Change: Updated checkbox and radiobutton components
We updated the OcCheckbox and OcRadio components so that it's possible to use them properly with `v-model`. OcRadio had
the radiobutton on the right side of the label. We moved it over to the left side for consistency.
https://github.com/owncloud/owncloud-design-system/pull/890
| owncloud/web/packages/design-system/changelog/1.12.0_2020-10-03/radio-and-checkbox-components.md/0 | {
"file_path": "owncloud/web/packages/design-system/changelog/1.12.0_2020-10-03/radio-and-checkbox-components.md",
"repo_id": "owncloud",
"token_count": 93
} | 645 |
Bugfix: Fix oc-autocomplete
We fixed a bug in OcAutocomplete which was introduced with the removal of lodash as a dependency.
https://github.com/owncloud/owncloud-design-system/pull/710
| owncloud/web/packages/design-system/changelog/1.2.2_2020-04-08/710/0 | {
"file_path": "owncloud/web/packages/design-system/changelog/1.2.2_2020-04-08/710",
"repo_id": "owncloud",
"token_count": 57
} | 646 |
Enhancement: Automatically focus modal
When the modal is mounted, it receives automatically a focus.
The focus is sent directly to the modal itself so skipping the wrapping div which works only as a background.
https://github.com/owncloud/owncloud-design-system/pull/781 | owncloud/web/packages/design-system/changelog/1.7.0_2020-06-17/modal-focus/0 | {
"file_path": "owncloud/web/packages/design-system/changelog/1.7.0_2020-06-17/modal-focus",
"repo_id": "owncloud",
"token_count": 68
} | 647 |
Change: Replace vue-datetime with v-calendar in our datepicker component
We've added `v-calendar` dependency so that we can use it as our datepicker component.
By doing so, we removed the old datepicker library that we use, `vue-datetime`.
https://github.com/owncloud/owncloud-design-system/pull/1661
| owncloud/web/packages/design-system/changelog/11.0.0_2021-10-04/change-datepicker-lib-to-v-calendar/0 | {
"file_path": "owncloud/web/packages/design-system/changelog/11.0.0_2021-10-04/change-datepicker-lib-to-v-calendar",
"repo_id": "owncloud",
"token_count": 91
} | 648 |
Enhancement: Relative date tooltips in the OcTableFiles component
Relative dates like "1 day ago" now have a tooltip that shows the absolute date. The following dates in the files table are affected:
* modify date
* share date
* delete date
https://github.com/owncloud/owncloud-design-system/pull/1787
https://github.com/owncloud/web/issues/5672
| owncloud/web/packages/design-system/changelog/11.3.0_2021-12-03/enhancement-add-accentuated-property/0 | {
"file_path": "owncloud/web/packages/design-system/changelog/11.3.0_2021-12-03/enhancement-add-accentuated-property",
"repo_id": "owncloud",
"token_count": 98
} | 649 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.