Skip to content

Commit

Permalink
BW-739 #comment store user id in meta data and check while delete image
Browse files Browse the repository at this point in the history
  • Loading branch information
jitendraashutec committed Apr 1, 2020
1 parent c6d8059 commit 32f358c
Show file tree
Hide file tree
Showing 6 changed files with 43 additions and 28 deletions.
3 changes: 2 additions & 1 deletion firestorage-rules.txt
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,8 @@ function isAuthenticated() {
match /questions {
// questions files, only authenticated user (for now)
match /{allFiles=**} {
allow read, write: if request.auth != null;
allow write, delete: if request.auth != null;
allow read;
}
}
match /bulk_upload/{userId} {
Expand Down
10 changes: 6 additions & 4 deletions functions/controllers/question.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,10 +196,10 @@ export class QuestionController {

static async uploadQuestionImage(req, res): Promise<any> {
const questionImage = req.body.image;
const userId = req.user.uid;
if (questionImage) {
const imageName = new Date().getTime();
await QuestionService.uploadImage(questionImage, imageName);
// QuestionService.generateQuesitonImage(imageName);
await QuestionService.uploadImage(questionImage, imageName, userId);
Utils.sendResponse(res, interceptorConstants.SUCCESS, { name: imageName });
} else {
Utils.sendResponse(res, interceptorConstants.SUCCESS, ResponseMessagesConstants.UNPUBLISHED_STATUS_CHANGED);
Expand All @@ -210,6 +210,7 @@ export class QuestionController {
const imageName = req.params.imageName;
if (imageName) {
try {

const stream = await QuestionService.generateQuesitonImage(imageName);
res.setHeader(HeaderConstants.CONTENT_DASH_DISPOSITION,
HeaderConstants.ATTACHMENT_QUESTION_IMAGE_PNG);
Expand Down Expand Up @@ -240,10 +241,11 @@ export class QuestionController {

static async deleteQuestionImage(req, res) {
const imageName = req.params.imageName;
const userId = req.user.uid;
if (imageName) {
try {
QuestionService.deleteQuestionImage(imageName)
Utils.sendResponse(res, interceptorConstants.SUCCESS, { 'message': 'Deleted!' });
const result = await QuestionService.deleteQuestionImage(imageName,userId)
Utils.sendResponse(res, interceptorConstants.SUCCESS, result);
} catch (error) {
Utils.sendError(res, error);
}
Expand Down
2 changes: 1 addition & 1 deletion functions/routes/question-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class QuestionRoutes {

// 'deleteQuestionImage/:imageName'
this.questionRoutes.delete(`/:${RoutesConstants.DELETE_DASH_QUESTION_DASH_IMAGE}/:${RoutesConstants.IMAGE_NAME}`,
QuestionController.deleteQuestionImage);
AuthMiddleware.authorizedOnly,QuestionController.deleteQuestionImage);

}
}
Expand Down
19 changes: 13 additions & 6 deletions functions/services/question.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,14 +83,14 @@ export class QuestionService {
}


static async uploadImage(image: String, imageName: number): Promise<any> {
static async uploadImage(image: String, imageName: number, userId:string): Promise<any> {

let filePath =
`questions`;
const imageBase64 = image.replace(/^data:image\/\w+;base64,/, '');
let bufferStream = new Buffer(imageBase64, GeneralConstants.BASE64);
try {
await QuestionService.uploadQImage(bufferStream, 'image/jpeg', filePath, imageName);
await QuestionService.uploadQImage(bufferStream, 'image/jpeg', filePath, imageName, userId);
return;

} catch (error) {
Expand All @@ -102,7 +102,7 @@ export class QuestionService {
* upload Question Image
* return status
*/
static async uploadQImage(data: any, mimeType: any, filePath: string, imageName: number): Promise<any> {
static async uploadQImage(data: any, mimeType: any, filePath: string, imageName: number,userId: string): Promise<any> {
const stream = require('stream');
const file = QuestionService.bucket.file(`${filePath}/${imageName}`);
const dataStream = new stream.PassThrough();
Expand All @@ -115,7 +115,8 @@ export class QuestionService {
metadata: {
contentType: mimeType,
metadata: {
custom: QuestionsConstants.META_DATA
custom: QuestionsConstants.META_DATA,
userId: userId,
}
}
}))
Expand Down Expand Up @@ -177,9 +178,15 @@ export class QuestionService {
}
}

static async deleteQuestionImage(imageName: string) {
static async deleteQuestionImage(imageName: string, userId: string) {
const file = QuestionService.bucket.file(`questions/${imageName}`);
return file.delete();
const metaData = await file.getMetadata();
if(metaData && metaData[0].metadata.userId && metaData[0].metadata.userId === userId){
file.delete();
return {'message': 'Deleted !!!'};
} else{
return {'message': 'Your have no permission to delete image'};
}
}

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ import { FormBuilder, FormGroup, Validators, FormArray, FormControl } from '@ang
import { Question, QuestionStatus, Category, User, Answer, ApplicationSettings } from '../../model';
import { QuestionService } from '../../../core/services';
import { Observable, interval, of, Subject, merge } from 'rxjs';
import { debounceTime, switchMap, map, multicast, take, skip} from 'rxjs/operators';
import { debounceTime, switchMap, map, multicast, take, skip, mergeMap} from 'rxjs/operators';
import { AutoUnsubscribe } from 'ngx-auto-unsubscribe';
// import { QuillImageUpload } from 'ng-quill-tex/lib/models/quill-image-upload';
import { CropImageDialogComponent } from './../crop-image-dialog/crop-image-dialog.component';
import { MatDialog } from '@angular/material';
import { Store, select } from '@ngrx/store';
import { CoreState, coreState } from './../../../core/store';
import { CoreState, coreState, QuestionActions } from './../../../core/store';
import * as userActions from '../../../../../../trivia/src/app/user/store/actions';
import { Utils } from 'shared-library/core/services';
@Component({
Expand Down Expand Up @@ -56,7 +56,8 @@ export class QuestionFormComponent implements OnInit, OnChanges, OnDestroy {
public dialog: MatDialog,
public questionService: QuestionService,
public store: Store<CoreState>,
public utils: Utils) {
public utils: Utils,
public questionAction: QuestionActions) {


}
Expand Down Expand Up @@ -309,6 +310,9 @@ export class QuestionFormComponent implements OnInit, OnChanges, OnDestroy {
onTextChanged(text) {
this.quillObject.jsonObject = text.delta;
this.quillObject.questionText = text.html;
if(text.imageParsedName){
    this.store.dispatch(this.questionAction.deleteQuestionImage(text.imageParsedName));
}
}

// Image Upload
Expand All @@ -321,20 +325,21 @@ export class QuestionFormComponent implements OnInit, OnChanges, OnDestroy {
});

this.dialogRef.componentInstance.ref = this.dialogRef;
this.subscriptions.push(this.dialogRef.componentInstance.ref.afterClosed().subscribe(result => {
if (result) {
const fileName = `questions/${new Date().getTime()}-${file.name}`;
this.questionService.saveQuestionImage(result.image, fileName).subscribe(uploadTask => {
if (uploadTask != null) {
if (uploadTask.task.snapshot.state === 'success') {
this.questionService.getQuestionDownloadUrl(fileName).subscribe(imageUrl => {
quillImageUpload.setImage(imageUrl);
});
}
}
});
}
this.subscriptions.push(this.dialogRef.componentInstance.ref.afterClosed()
.pipe(mergeMap(result => {
const fileName = `questions/${new Date().getTime()}-${file.name}`;
return this.questionService.saveQuestionImage(result['image'], fileName);
}),
mergeMap(image => {
 return of(this.utils.getQuestionUrl(`${image['name']}`) + `?d=${new Date().getTime()}`);
})
).subscribe(imageUrl => {
// SetImage callback function called to set image in editor
quillImageUpload.setImage(imageUrl);
// this.cd.markForCheck();
}));


}

}
Binary file modified quill-blot-formatter-1.0.4.tgz
Binary file not shown.

0 comments on commit 32f358c

Please sign in to comment.